简体   繁体   English

KnockoutJS自定义绑定无法在可观察到的更改上触发更新回调

[英]KnockoutJS custom binding cannot trigger update callback on observable change

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: 我的ViewModel是这样的:

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: 而html是:

<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. 当'self.opts'可观察的数组更改时,我无法触发更新。 Please help me. 请帮我。 'init' and 'update' callback are called once at the beginning. “ init”和“ update”回调在开始时被调用一次。 After that when i get observable changed the update callback is not called. 之后,当我观察到更改时,不会调用更新回调。

JSFiddle - Using setTimeout to mimic ajax call. JSFiddle-使用setTimeout模仿ajax调用。

You weren't setting "opts" correctly in the ajax callback. 您没有在ajax回调中正确设置“ opts”。 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 您也有一些格式错误的HTML

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM