[英]KnockoutJS custom binding cannot trigger update callback on observable change
當我的可觀察數組發生更改時,不會觸發更新回調。 請幫忙。 這是我的自定義綁定:
ko.bindingHandlers.selectizeBinding ={
update: function(element, valueAccessor){
var value = valueAccessor();
var ords = ko.unwrap(value);
alert(ords);
},
init: function(){},
}
我的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;
});
}
而html是:
<select data-bind="value: order_id">
<option value="1">option1</option>
<option value="2">option2</option>
<select data-bind="selectizeBinding: opts"</select>
當'self.opts'可觀察的數組更改時,我無法觸發更新。 請幫我。 “ init”和“ update”回調在開始時被調用一次。 之后,當我觀察到更改時,不會調用更新回調。
JSFiddle-使用setTimeout
模仿ajax調用。
您沒有在ajax回調中正確設置“ opts”。 需要使用功能進行設置。
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;
});
}
您也有一些格式錯誤的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.