0
votes

When my observable array is changed, the update callback is not triggered. Please help. Here is my custom binding:

ko.bindingHandlers.selectizeBinding ={
    update: function(element, valueAccessor){
        var value = valueAccessor();
        var ords = ko.unwrap(value);
        alert(ords);
    },
    init: function(){},
}

My ViewModel is like this:

function poReceivingModel(){
    var self = this;
    self.order_id = ko.observable();
    self.opts = ko.observableArray(); 
    self.getOptions = ko.computed(function(){
        var odr_id = ko.unwrap(self.order_id)
        var url = '/po/order_products_asjson/' + String(odr_id)
            if(typeof(odr_id) != 'undefined'){
                $.ajax({
                    url: url,
                    dataType: 'json',
                    async: false,
                    success: function(data) {
                        self.opts = data.options;
                    }
                });
            }
        return self.opts;
    });
}

And html is:

<select data-bind="value: order_id">
    <option value="1">option1</option>
    <option value="2">option2</option>
<select data-bind="selectizeBinding: opts"</select>

I cannot get update triggered when 'self.opts' observable array changes. Please help me. 'init' and 'update' callback are called once at the beginning. After that when i get observable changed the update callback is not called.

1

1 Answers

1
votes

JSFiddle - Using setTimeout to mimic ajax call.

You weren't setting "opts" correctly in the ajax callback. It needs to be set with a function.

function poReceivingModel(){
    var self = this;
    self.order_id = ko.observable();
    self.opts = ko.observableArray(); 
    self.getOptions = ko.computed(function(){
        var odr_id = ko.unwrap(self.order_id)
        var url = '/po/order_products_asjson/' + String(odr_id)
            if(typeof(odr_id) != 'undefined'){
                $.ajax({
                    url: url,
                    dataType: 'json',
                    async: false,
                    success: function(data) {
                        self.opts(data.options);
                    }
                });
            }
        return self.opts;
    });
}

You also had some malformed HTML

<select data-bind="value: order_id">
    <option value="1">option1</option>
    <option value="2">option2</option>
</select>

<select data-bind="selectizeBinding: opts"</select>