Question

KnockoutJS with WebApi. When I tried with custom binding, I can not pass the binding data into the custom binding function.

I'm banging my head for two days now, definitely missing something here.

Any guideline, articles or sample code would be greatly appreciated. Thanks a lot.

<script>
function ViewModel() {
    var self = this;
    self.items = ko.observableArray();

    // This is getting data, and tested have data returned.
    var baseUri = 'api/items';
    $.getJSON(baseUri, self.items);
}

$(document).ready(function () {
    ko.bindingHandlers.testBinding = {
        init: function (element, valueAccessor) {
            var value = valueAccessor();
            var valueUnwrapped = ko.utils.unwrapObservable(value);
            // This is always 0.
            alert(valueUnwrapped.length);
        },
        update: function (element, valueAccessor) {
            var value = valueAccessor();
            var valueUnwrapped = ko.utils.unwrapObservable(value);
            // This is always 0.
            alert(valueUnwrapped.length);
        }
    };

    // Binding to Web Api data.
    ko.applyBindings(new ViewModel());

    // Test it with static data, and custom binding works. The length displayed 2. 
    //var viewModel = {
    //  items: ko.observableArray([{name: "Bob1"}, {name: "Bob2"}])
    //};
    //ko.applyBindings(viewModel);

});
</script>
<div data-bind="testBinding: items"></div>
Was it helpful?

Solution

init will always be zero because the data is populated async (So when you databind the array will be empty).

Update should be zero once, and then next time return correct length..

Test this little fiddle

http://jsfiddle.net/SVQhR/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top