javascript属性改变事件

发布于 2024-10-01 16:27:29 字数 267 浏览 8 评论 0原文

我需要在每次更新/更改属性时触发一个事件,以便使 dom 元素与模型上的属性值保持同步(我使用 john resig 的简单继承 http://ejohn.org/blog/simple-javascript-inheritance/)。这可以通过跨浏览器的方式实现吗?在我看来,如果我可以包装 js 用于设置属性的任何函数并使其触发一个事件,那么它就可以工作,我只是不知道该怎么做。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

终遇你 2024-10-08 16:27:29

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

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

$(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 doesn't use a function to set properties. They're just variables, and setting them doesn't require any elaborate wrappers.

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');
末骤雨初歇 2024-10-08 16:27:29

也许您已经使用 jQuery 绑定/触发解决了您的问题,但我想告诉您,我正在构建一个更改跟踪和(在此之上)实体建模 Javascript 框架,名为“帐篷”,它可以解决您暴露的问题,而不需要有关对象操作的任何特殊语法,其开源并托管于:

https://github.com/benjamine/tent

它使用 JSDoc 进行记录,并使用 js-test-driver 进行单元测试。

您可以通过这种方式使用更改跟踪模块:

   var myobject = { name: 'john', age: 34 };

   // add a change handler that shows changes on alert dialogs
   tent.changes.bind(myobject, function(change) {
       alert('myobject property '+change.data.propertyName+' changed!');
   });

   myobject.name = 'charly'; // gets notified on an alert dialog

它也适用于数组更改(添加、删除)。
此外,您可以使用“实体”上下文来保留所有检测到的更改(添加、删除、修改项目)的更改集,这些更改按集合分组、级联添加和删除、保持反向属性同步、跟踪 1 对 1、1 对 N以及 N 对 M 关系等。

Maybe you already solved your problem with jQuery bind/trigger, but I wanted to tell that I'm building a Change Tracking and (in top of that) Entity Modeling Javascript Framework, named "tent" that solves the problem you exposed, without requiring any special syntax on object manipulation, its open source and hosted at:

https://github.com/benjamine/tent

It's documented with JSDoc and unit tested with js-test-driver.

you can use the change tracking module this way:

   var myobject = { name: 'john', age: 34 };

   // add a change handler that shows changes on alert dialogs
   tent.changes.bind(myobject, function(change) {
       alert('myobject property '+change.data.propertyName+' changed!');
   });

   myobject.name = 'charly'; // gets notified on an alert dialog

it works with Array changes too (adds, deletes).
Further you can use "Entity" Contexts to keep a changesets of all detected changes (ADDED, DELETED, MODIFIED items) grouped on collections, cascade adds and deletes, keep reverse properties synced, track 1-to-1, 1-to-N and N-to-M relationships, etc.

蝶舞 2024-10-08 16:27:29

对象defineProperty/defineProperties 就可以解决这个问题。
这是一个简单的代码。我基于此构建了一些数据绑定框架,它可能会变得非常复杂,但要像这样练习:

var oScope = {
    $privateScope:{},
    notify:function(sPropertyPath){
        console.log(sPropertyPath,"changed");
    }
};
Object.defineProperties(oScope,{
    myPropertyA:{
        get:function(){
            return oScope.$privateScope.myPropertyA
        },
        set:function(oValue){
            oScope.$privateScope.myPropertyA = oValue;
            oScope.notify("myPropertyA");
        }
    }
});

oScope.myPropertyA = "Some Value";
//console will log: myPropertyA changed

Object defineProperty/defineProperties does the trick.
Here goes a simple code. I have built some data binding frameworks based on that, and it can get really complex, but for exercising its like this:

var oScope = {
    $privateScope:{},
    notify:function(sPropertyPath){
        console.log(sPropertyPath,"changed");
    }
};
Object.defineProperties(oScope,{
    myPropertyA:{
        get:function(){
            return oScope.$privateScope.myPropertyA
        },
        set:function(oValue){
            oScope.$privateScope.myPropertyA = oValue;
            oScope.notify("myPropertyA");
        }
    }
});

oScope.myPropertyA = "Some Value";
//console will log: myPropertyA changed
落花浅忆 2024-10-08 16:27:29

您可以尝试 Javascript 属性事件 (jpe.js)

我遇到了类似的问题,最终为 Object.defineProperty 编写了一个重载函数,将事件处理程序添加到属性中。它还提供类型检查(js-base-types)并在内部存储其值,防止不必要的更改。

正常的 DefineProperty 示例:

Object.defineProperty(document, "property", {
    get:function(){return myProperty},
    set:function(value){myProperty = value},
})
var myProperty = false;

具有 onchange 事件的属性示例:

Object.defineProperty(document, "property", {
    default:false,
    get:function(){},
    set:function(value){},
    onchange:function(event){console.info(event)}
})

You could try Javascript Property Events (jpe.js)

I encountered a similar issue, and ended up writing an overload function for Object.defineProperty that adds event handlers to the properties. It also provides type checking (js-base-types) and stores its value internally, preventing unwanted changes.

Sample of normal defineProperty:

Object.defineProperty(document, "property", {
    get:function(){return myProperty},
    set:function(value){myProperty = value},
})
var myProperty = false;

Sample of property with onchange event:

Object.defineProperty(document, "property", {
    default:false,
    get:function(){},
    set:function(value){},
    onchange:function(event){console.info(event)}
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文