0

我创建了一个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,就好像它只将所有内容绑定到列表中的最后一项一样。我一生都无法弄清楚我做错了什么。

4

2 回答 2

1

您需要创建一个闭包,以便循环的每次迭代for都有自己的private_variable对象。否则,每次迭代只会覆盖前一次(因为private_variable被提升到其范围的顶部)。我会这样设置:

var ObservablePropertyList = (function () {
    "use strict";

    var handleAccess = function (propList, key, callback) {
        var privValue = {};

        propList["get_" + key] = function () {
            return privValue;
        };
        propList["set_" + key] = function (value) {
            // Set the value
            privValue = value;

            // Invoke the callback
            callback(value);
        };
    };

    return function (coll) {
        var propertyList = {}, index;

        for (index in coll) {
            handleAccess(propertyList, index, coll[index]); 
        }

        return propertyList;
    };
}());

var boundProperties = ObservablePropertyList({
    TheTime: function (value) {
        $('#thetime').text(value);
    },
    TheDate: function (value) {
        $('#thedate').text(value);
    }
}), number = 0;

setInterval(function () {
    boundProperties.set_TheTime(new Date());
    boundProperties.set_TheDate(number++);
}, 500);

演示:http: //jsfiddle.net/PXHDT/

于 2013-07-22T20:46:47.077 回答
1

当使用这样的循环时,您需要将其包裹在外壳中

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;
}
于 2013-07-22T20:33:25.327 回答