我创建了一个 ObservablePropertyList ,它应该在属性更改时执行回调。实现是:
function ObservablePropertyList(nameCallbackCollection) {
var propertyList = {};
for (var index in nameCallbackCollection) {
var private_value = {};
propertyList["get_" + index] = function () { return private_value; }
propertyList["set_" + index] = function (value) {
// Set the value
private_value = value;
// Invoke the callback
nameCallbackCollection[index](value);
}
}
return propertyList;
}
这是一个快速测试演示:
var boundProperties = BoundPropertyList({
TheTime: function (value) {
$('#thetime').text(value);
},
TheDate: function (value) {
$('#thedate').text(value);
}
});
var number = 0;
setInterval(function () {
boundProperties.set_TheTime(new Date());
boundProperties.set_TheDate(number++);
}, 500);
但由于某种原因,属性未正确分配或发生其他原因。也就是说,由于某种原因调用 set_TheTime
会执行 set_TheDate
的回调,几乎就像将所有内容都绑定(bind)到列表中的最后一项一样。我一生都无法弄清楚我做错了什么。
最佳答案
当使用这样的循环时,您需要将其包裹在外壳中
function ObservablePropertyList(nameCallbackCollection) {
var propertyList = {};
for (var index in nameCallbackCollection) {
(function(target){
var private_value = {};
propertyList["get_" + index] = function () { return private_value; }
propertyList["set_" + index] = function (value) {
// Set the value
private_value = value;
// Invoke the callback
target(value);
}
})(nameCallbackCollection[index]);
}
return propertyList;
}
关于javascript - 为什么我的属性分配不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17796817/