2

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

<!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>
4

2 回答 2

2

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

于 2013-02-11T06:36:09.023 回答
0

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

updateBinding: People().Records()

应该:

updateBinding: People().Records

稍作调整:http : //jsfiddle.net/twRFf/3/

于 2013-02-04T00:17:18.360 回答