2
votes

Im using knockoutjs and try to setup a project including ko.mapping and a custom update binding for an observableArray. When setting value directly, the update binding fires once, when using ko.mapping.fromJS, the update binding fires twice. See Fiddle or code below:

<!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
I am not sure what else you are doing, but this does not happen for me. Can you post a fiddle that reproduces the issue you are seeing? jsfiddle.net/tyrsius/Sgsh6 - Kyeotic
It's impossible for us to give you a reasonable answer until you show us your markup as well. There are probably other factors in your markup that is causing this to happen. - Jeff Mercado
I modified the sample (the previous was indeed wrong) and made it as simple as possible to reproduce my problem. - Dresel

2 Answers

2
votes

This was a bug by knockout.mapping when embedding arrays in regular objects and is now fixed (see github).

0
votes

You don't need to use full function calling syntax in your binding for updateBinding as it's not an expression.

updateBinding: People().Records()

should be:

updateBinding: People().Records

Tweaked a bit: http://jsfiddle.net/twRFf/3/