开发者

Object access fire event

I have an object that I creat开发者_开发技巧ed previously.

obj = new Object();

I would like to fire a function each time this one of the object child is changed.

ex:

function changed()
{
  alert('Object changed';)
}

obj.test = 'blabla'; //fire changed().

Is this possible? Thank you


Yes and no. What you're looking for are accessors and mutators (also known as getters and setters), but unfortunately they're not cross-browser compatible.

If you just need to notice that the value has changed, and delays aren't an issue, you could use a timeout loop for polling the value:

function check(key, context, callback)
{
  var cachedValue;
  cachedValue = context[key];
  function doCheck()
  {
    if ( cachedValue != context[key] ) callback();
    setTimeout(doCheck, 100);
  }
  doCheck();
}

check('test', obj, testChanged);

This is, of course, a very simple example of how a polling loop could work. There are better ways of doing this.


If for compatibility reasons you do not wish to use Javascript getters/setters (they are fairly new -- added to the 5th edition of ECMA-262 in 2009) then perhaps, if your context allows, try creating setter functions instead:

setVariable(value)

For this to work, your code would have to be updated to call these functions instead of setting properties.

I understand that this may not be possible if an external library (or other code) is updating the property. The polling approach that was suggested is otherwise a good solution, as long as an asynchronous notification is sufficient (of course it would not be able to notify of intermediate values, that is values that are set in between the interval).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜