我刚刚第一次阅读了淘汰图书馆网站的入门文档,并对如何在发送到淘汰赛的回调函数中指定 this 关键字的目标有疑问strong> subscribe 函数,用于跟踪对正在观察其属性的对象的集的更改。
我需要跟踪其属性最初为null的100个对象。这100个对象中的每一个都可以用相同的视图模型来描述:
var myViewModel = {
personName: ko.observable(null),
personAge: ko.observable(null)
};
var my100 = {
a1: myViewModel,
a2: myViewModel,
.
.
.
a100: myViewModel
}
subscribe()函数的第二个参数“定义了回调函数中 this 的值”。 http://knockoutjs.com/documentation/observables.html
当我需要知道这100个对象中的哪一个已经改变时,我不确定第二个参数是什么。当视图模型中的任何属性从null更改为值或从一个值更改为另一个值时,我想知道中发生更改的对象,例如的 A88 即可。
myViewModel.personName.subscribe(myCallback, ?, "change");
myViewModel.personAge.subscribe(myCallback, ?, "change");
知道哪个属性被更改也会很好,但更重要的是我知道属性已更改的对象。
答案 0 :(得分:0)
在正确的范围内保存对视图模型本身的引用可能更容易,因此它可用于回调。如果使用构造函数构造视图模型,则稍微更具可读性:
var Person = function() {
var self = this;
self.personName = ko.observable(null);
self.personAge= ko.observable(null);
self.personName.subscribe(function(newValue) {
// "self" is a variable reference to the correct Person here
// newValue is the new value for the observable
// calling "myCallback" here allows you to pass those at your leisure
});
};
请参阅this fiddle了解其运作方式。
PS。如果回调很短,您可能甚至不需要单独的myCallback
函数,只需在subscribe
调用中内联函数内部进行操作,您已经在其中引用了正确的this
值(保存在self
变量中)。