淘汰赛自定义绑定如何与 observableArray 一起使用?当使用带有自定义绑定的 ko.observable() 时,一切都按预期工作。使用 ko.observableArray() 时,只会抛出初始事件(init 和 update 一次),但不会检测到进一步的更改(参见Fiddle或下面的代码)。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="knockout-2.2.1.js"> </script>
</head>
<body>
<div data-bind="text: Observable, updateBinding: Observable"></div>
<div data-bind="foreach: ObservableArray, updateBinding: ObservableArray">
<span data-bind="text: $data"></span>
</div>
<script type="text/javascript">
ko.bindingHandlers['updateBinding'] = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
alert("Binding Handler (Init)");
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
alert("Binding Handler (Update)");
}
};
function ViewModel() {
var self = this;
self.ObservableArray = ko.observableArray();
self.Observable = ko.observable();
}
var viewModel = new ViewModel();
// Fires Init + Update for Observable and ObservableArray
ko.applyBindings(viewModel);
// Fires Update for Observable
viewModel.Observable(1);
// Does nothing
viewModel.ObservableArray.push('1');
</script>
</body>
</html>