javascript属性更改事件 [英] javascript property change event

查看:98
本文介绍了javascript属性更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在每次更新/更改属性时都触发一个事件,以使dom元素与模型上的属性值保持同步(我使用john resig的简单继承

I need to fire an event every time a property is updated/changed in order to keep dom elements in sync with the property values on the model (Im using john resig's simple inheritance http://ejohn.org/blog/simple-javascript-inheritance/). Is this possible to do in a cross-browser way? It seems to me that if I could wrap whatever function js uses to set properties and make it fire an event, that it could work, Im just not sure how to do that.

推荐答案

JavaScript不使用函数来设置属性.它们只是变量,设置它们不需要任何复杂的包装.

JavaScript doesn't use a function to set properties. They're just variables, and setting them doesn't require any elaborate wrappers.

可以使用函数来设置属性-与您在支持类中的私有数据的语言中使用的getter/setter布置相同.这样,您的函数可以轻松运行已注册为回调的其他函数.使用jQuery,您甚至可以将它们作为事件来处理.

You could use a function to set the property, though — the same sort of a getter/setter arrangement you might use in a language that supported private data in classes. In that way your function could easily run other functions that have been registered as callbacks. Using jQuery you can even handle those as events.

$(yourObject).bind('some-event-you-made-up', function() { 
    // This code will run whenever some-event-you-made-up is triggered on yourObject
});

// ... 

$(yourObject).trigger('some-event-you-made-up');

这篇关于javascript属性更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆