Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout + customBinding not updating

Tags:

knockout.js

I have a quick question about customBindings, hopefully some could help explain to me? I thought that when an observable is updated that any customBinding that is bound to that observable would have its "update" method called. I can see that when I update my observable that other subscribers are being notified, but it doesn't seem that the customBinding is being called.

Here is my viewModel:

var innerModel = {
    name: ko.observable('junk')
};

var innerModel2 = {
    name: ko.observable('junk2')
};

var viewModel = {
    im1: innerModel,
    im2: innerModel2,
    selectedModel: ko.observable({name:'xxx'})
};

and here is my customBinding:

ko.bindingHandlers.custom = {
    update: function(element, valueAccessor) {
        console.log("BAM!");
        while (element.firstChild)
            ko.removeNode(element.firstChild);

        ko.renderTemplate('test', valueAccessor(), {}, element, 'replaceNode');

    }  
};

where my template is simply a span that displays the "name" field:

<script id='test' type='text/html' charset='utf-8'>
<span data-bind='text: name'></span>
</script>

Here is the HTML that I use with the customBinding:

<div id="container" data-bind="with: viewModel">
    <div data-bind="custom: selectedModel">
    </div>
</div>

When I update selectedModel to either of the two innerModels, the correct name is displayed but the customBinding's 'update' function isn't being called. I have a separate subscriber to the "selectedModel" observable:

viewModel.selectedModel.subscribe(function(newValue) {
    console.log(newValue.name());
});

and that is called when I change the selectedModel, so why isn't the customBinding's update being called?

Here is a jsfiddle that shows the issue: http://jsfiddle.net/gperng/twAcJ/

Any help would be appreciated!

like image 807
Ginger P Avatar asked Mar 01 '12 07:03

Ginger P


1 Answers

You need to call the following function to make it work:

var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor())

Try this fiddle for more: http://jsfiddle.net/twAcJ/13/

like image 132
KunYan Avatar answered Dec 10 '22 20:12

KunYan