【发布时间】:2012-06-06 15:40:23
【问题描述】:
这可能看起来很愚蠢,但在当今时代,如果数组的内容发生了变化,人们应该能够期望 JS 引发事件。
关于在变量更改(定义 getter 或 setter)时获得通知的几个问题。而且似乎有a way to do that(至少对于大多数浏览器,包括IE6+)
我的问题是,如果数组中的项目发生更改,我会尝试收到通知:
var ar = ["one", "two", "three"];
// setting the whole array will call the custom setter method
// (assuming you defined it)
ar = ["one", "three", "five"];
// however, this will only call the getter method and won't call the setter
// without defining custom setters for every item in the array.
ar[1] = "two";
显然,我试图避免强迫编码人员使用老式 Java 风格的 .getVale() 和 .setValue() 函数来访问/修改数据。
【问题讨论】:
-
Backbone.js 可以在集合模型发生变化时触发事件。不完全相同,但你可以看到他们是如何做到的。
-
您可以将数组作为对象的私有变量,然后更改变量的唯一方法是在该对象上使用可以触发事件的方法...
-
我认为你应该阅读observable pattern
-
stackoverflow.com/questions/2449182/… 的可能重复项看起来您可以在数组上使用defineGetter/defineSetter,但只能用于固定键。
You can't define a property for “all names that happen to be integers” all in one go. -
@asawyer、Abe 和 MilkyWayJoe:很好的建议,但它们都需要修改现有语法 array[indexz] = x;德米特里:不要认为重复,但 bobince 的一篇很棒的帖子。这意味着 JS 需要一个 onProperyAdded 钩子,然后动态地将自定义 getter setter 添加到数组项中。如果你们中的某个人想将其发布为答案,请认为我们在那里。
标签: javascript cross-browser dom-events