当使用带有observableArray的ko.mapping时,为什么更新绑定会触发两次?

时间:2013-02-01 17:17:01

标签: knockout.js knockout-mapping-plugin

我正在使用knockoutjs并尝试设置一个项目,包括ko.mapping和observableArray的自定义更新绑定。直接设置值时,更新绑定会触发一次,当使用ko.mapping.fromJS时,更新绑定会触发两次。请参阅Fiddle或以下代码:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="knockout-2.2.1.js"> </script>
    <script type="text/javascript" src="knockout.mapping.js"></script>
</head>
<body>
    <div data-bind="foreach: ObservableArray, updateBinding: ObservableArray">
        <span data-bind="text: Value"></span>
    </div>
    <script type="text/javascript">
        ko.bindingHandlers['updateBinding'] = {
            init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                console.log("Binding Handler (Init)");
            },
            update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                console.log("Binding Handler (Update)");
                var data = ko.utils.unwrapObservable(valueAccessor());
            }
        };

        function MainViewModel() {
            var self = this;

            self.ObservableArray = ko.observableArray();
        }

        var viewModel = new MainViewModel();

        // Fires Init + Update for ObservableArray
        ko.applyBindings(viewModel);

        // Setting directly fires Update for ObservableArray once
        viewModel.ObservableArray([{ "Value": "Lucky Luke" }]);

        // Setting via mapping fires Update for ObservableArray twice
        ko.mapping.fromJS({ "ObservableArray": [{ "Value": "Ludwig van Beethoven" }] }, {}, viewModel);
    </script>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

这是在常规对象中嵌入数组时knockout.mapping的错误,现在已修复(请参阅github)。

答案 1 :(得分:0)

您不需要在updateBinding的绑定中使用完整函数调用语法,因为它不是表达式。

updateBinding: People().Records()

应该是:

updateBinding: People().Records

稍微调整一下:http://jsfiddle.net/twRFf/3/