[英]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. 使用以下代码,我希望每次更新viewModel.item observable时都会执行更新函数。 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. 我可以看到我的init和更新函数按照预期在页面加载时触发,但是当我单击我的按钮更新observable的值时则不会。
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 . 我在这里创建了一个JSFiddle。
The update
function of a binding handler will run whenever the observables it accesses are updated. 只要更新了它访问的observable,绑定处理程序的update
功能就会运行。 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');
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.