我是淘汰赛的新手。我无法理解示例中的一个技巧。这是我的代码。我创建了 3 个用户......下面显示了我创建第三个用户时的处理输出。
// It's my view
<div id="page-container">
<input type="text" data-bind="value: usernameInput" />
<button data-bind="click: addPerson">Добавить</button>
<ul data-bind="foreach: users">
<li data-bind="text: username"></li>
</ul>
</div>
<script>
// It's my UserModel
function UserModel(username, callback){
console.log('Start creating object...');
var self = this;
self.username = ko.observable(username);
self.updateCallback = ko.computed(function(){
console.log('updateCallback: ' + self.username());
callback(self);
return true;
});
};
// It's my ViewModel
function ViewModel(){
var self = this;
self.users = ko.observableArray([]);
self.usernameInput = ko.observable('');
self.addPerson = function(){
var u = self.usernameInput();
var um = new UserModel(u, self.update);
self.users.push(um);
console.log('Item Pushed');
self.usernameInput('');
console.log('Users Collection: ' + self.users());
};
self.update = function(item){
console.log('Update: ' + item.username());
ko.utils.arrayFilter(self.users(), function(it) {
});
};
};
ko.applyBindings(new ViewModel(), document.getElementById('page-container'));
这是我的控制台输出。
Start creating object...
updateCallback: 3
Update: 3
updateCallback: 1
Update: 1
updateCallback: 2
Update: 2
updateCallback: 3
Update: 3
Item Pushed
Users Collection: [object Object],[object Object],[object Object]
这部分我理解
Start creating object...
updateCallback: 3
Update: 3
但是当我尝试在 updateCallback 上下文中的 update 方法中调用此函数时:
ko.utils.arrayFilter(self.users(), function(it) {
});
它为每个用户计算了 3 次 updateCallback ...
任何人都可以解释“手指”为什么会发生这种情况......提前感谢您的回复......
f_martinez
这是因为您计算的 updateCallback 取决于整个用户 observableArray。这种依赖似乎是隐含的,但它是通过 callback(self);...
是的,这种依赖是隐含的......但是这种依赖对我来说还不清楚......
当我在更新中 使用LOOP时,如下所示: for(var i in self.users()){}它为每个用户计算 updateCallback 3 次...但是如果我删除循环并创建第三个用户...我会只得到这个输出:
Start creating object...
updateCallback: 3
Update: 3
Item Pushed
Users Collection: [object Object],[object Object],[object Object]
我无法理解updateCallback如何依赖于整个用户 observableArray ......我只使用简单的空循环并且不改变内部的任何东西......