我正在使用 knockoutjs 并尝试设置一个项目,包括 ko.mapping 和 observableArray 的自定义更新绑定。直接设置值时,更新绑定触发一次,使用 ko.mapping.fromJS 时,更新绑定触发两次。请参阅下面的小提琴或代码:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="knockout-2.2.1.js"> </script>
<script type="text/javascript" src="knockout.mapping.js"></script>
</head>
<body>
<div data-bind="foreach: ObservableArray, updateBinding: ObservableArray">
<span data-bind="text: Value"></span>
</div>
<script type="text/javascript">
ko.bindingHandlers['updateBinding'] = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
console.log("Binding Handler (Init)");
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
console.log("Binding Handler (Update)");
var data = ko.utils.unwrapObservable(valueAccessor());
}
};
function MainViewModel() {
var self = this;
self.ObservableArray = ko.observableArray();
}
var viewModel = new MainViewModel();
// Fires Init + Update for ObservableArray
ko.applyBindings(viewModel);
// Setting directly fires Update for ObservableArray once
viewModel.ObservableArray([{ "Value": "Lucky Luke" }]);
// Setting via mapping fires Update for ObservableArray twice
ko.mapping.fromJS({ "ObservableArray": [{ "Value": "Ludwig van Beethoven" }] }, {}, viewModel);
</script>
</body>
</html>