Question

I'm working on a custom binding that will fetch existing values and insert it into the viewmodel. However, I hit a snag where the element provided in ko.bindingHandlers doesn't seem to have any child elements.

Is this how things work in KnockoutJS or am I missing something?

Here is my HTML markup:

<div data-bind="with: person, useInitValueFor: ['firstName', 'lastName']">
    <div data-bind="text: firstName">John</div>
    <div data-bind="text: lastName">Doe</div>
</div>

And here's my JS code:

ko.bindingHandlers.useInitValueFor = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var $elem = $(element);
        var value = ko.utils.unwrapObservable(valueAccessor());
        var allBindings = allBindingsAccessor();

        for (var i = 0; i < value.length; i++) {
            var c = value[i];
            var e = $elem.children('[data-bind*="' + c + '"]:first');
            alert(e.length); // This gives me 0
            if (e.length > 0) {
                var a = e.attr('data-bind').split(',');
                for (var j = 0; j < a.length; j++) {
                    var b = a[j].split(':');

                    switch (b[0]) {
                        case 'text':
                            allBindings.with[c](b[1]);
                            alert(allBindings.with[c]());
                            break;
                    }
                }
            }
        }
    }
};

function personViewModel() {
    this.person = {
        firstName: ko.observable(),
        lastName: ko.observable()
    };
}

$(document).ready(function() {
    var vm = new personViewModel();
    ko.applyBindings(vm);
});

You can also see it here on jsFiddle: http://jsfiddle.net/dzul1983/XjD3Y/1/

Was it helpful?

Solution

The init function of the with binding copies off the children of the element to use as a "template". The update portion applies the current data against that "template".

So, when your binding's code runs, you are right in between the with binding's init and update.

One solution for you is to list your binding before the with binding.

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