frenchie
frenchie

Reputation: 51927

event handlers in javascript

I'm looking to build two functions:

var MyObject = new Object();
MyObject.MyProperty = 1;

function ListenToChange() {
  here I want to listen to changes in MyProperty1 and do something when it changes
}

function ThrowEvent () {
  here I change the value of MyProperty every 5 seconds
  setTimeOut('ThrowEvent', 5000);
}

I looked at the addEventListener property but it looks like it works for DOM objects. I thought of using the ThrowEvent function to change the value of a hidden div and listen for the changes in the value of the hidden with $('#HiddenDiv').change() but I'm wondering if there's a better way to do it with the addEventListener.

Thanks for your help.

Upvotes: 2

Views: 128

Answers (3)

RobG
RobG

Reputation: 147343

It seems that you are after ES5 set and get, however they won't work in an ECMAScript Ed 3 environment, you'll need to write your own getter and setter functions for that.

If you want to listen for changes to the DOM, there is a W3C DOM 2 Events specification that includes mutation events, however I don't think it was ever widely implemented. There is a level 3 working draft that deprecates a number of the level 2 features.

Upvotes: 0

user324312
user324312

Reputation:

I can infer from your example you're using jQuery; you could trigger a custom event anytime you change the value of your property:

var my_obj = {my_prop: 1}

function ListenToChange(event, newval) {
  console.log('my_prop is now' + newval)
}
$.bind("propchange:my_prop", ListenToChange)

function ThrowEvent () {
  $.trigger('propchange:my_prop', my_obj.my_prop)
  setTimeOut('ThrowEvent', 5000);
}

Upvotes: 1

mrtsherman
mrtsherman

Reputation: 39872

Well here is an example of what I came up with. It is not nearly as glamorous as John's example, but it gets the job done. Recommendations for improvements are more than welcome.

http://jsfiddle.net/yKYRs/

var MyObject = new Object();

MyObject.MyProperty = 1;

MyObject.MyProperty_Set = function(val) {   
    this.MyProperty = val;   
    ListenToChange();
}

function ListenToChange() {
    console.log('My Property was changed');
}

MyObject.MyProperty_Set(2);

Upvotes: 1

Related Questions