Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout custom binding update not firing

With the following code, I would expect my update function to execute every time the viewModel.item observable is updated. I can see my init and update functions firing on page load as expected, but not when my button is clicked which updates the observable's value.

Markup:

<button id='addButton'>item++</button>
<br/>
<span>viewModel.item = </span>
<span data-bind='text: $data.item(), bind: viewModel.item'></span>

Script:

$(document).ready(function() {
    $('#addButton').click(function() {
        viewModel.item(viewModel.item() + 1);
    });    
    var viewModel = {
        item: ko.observable(1)
    };        
    ko.bindingHandlers.bind = {
        init: function(element, valueAccessor) {
            alert('init');
        },
        update: function(element, valueAccessor) {
            alert('update');
        }  
    };        
    ko.applyBindings(viewModel);
}); 

I've browsed some of the similar questions and haven't found a comparable example. I've created a JSFiddle here.

like image 795
Citrus Avatar asked May 26 '14 22:05

Citrus


Video Answer


1 Answers

The update function of a binding handler will run whenever the observables it accesses are updated. Your function doesn't access any observables.

Here is an updated version that will work:

ko.bindingHandlers.bind = {
    init: function(element, valueAccessor) {
        alert('init');
    },
    update: function(element, valueAccessor) {
        ko.unwrap(valueAccessor());
        alert('update');
    } 
};        

http://jsfiddle.net/vMD74/14/

like image 80
Michael Best Avatar answered Sep 28 '22 19:09

Michael Best