我目前正在尝试学习 Knockout.JS - 我对 JavaScript 本身也比较陌生。
网站上有一个示例 - http://knockoutjs.com/examples/clickCounter.html - 我目前正在努力解决这个问题。
我已经在下面的代码中添加了一些我认为正在发生的事情的注释。还有一个关于函数如何工作的问题。
如果在 Knockout 方面更有经验的人能够准确解释那里发生了什么,那就太好了。谢谢。
(function() {
var clickCounterViewModel = function () {
// Here it looks like numberOfClicks is assigned the value 0 and wrapped in a ko.observable method
// that allows any changes of it to ripple throughout the application.
this.numberOfClicks = ko.observable(0);
// A function is created called registerClick and assigned to the ViewModel.
// The value of numberOfClicks is currently 0.
this.registerClick = function () {
// numberOfClicks is being used here as a method, but it was created as a property.
// It almost looks like I could write: this.numberOfClicks = this.numberOfClicks() + 1,
// however, that doesn't work. this.numberOfClicks is being passed into itself as an argument.
// Is this some sort of recursion? Can someone familiar with Knockout please explain how this is working?
this.numberOfClicks(this.numberOfClicks() + 1);
}
this.hasClickedTooManyTimes = ko.dependentObservable(function () {
return this.numberOfClicks() >= 3;
}, this);
};
ko.applyBindings(new clickCounterViewModel());
});
最佳答案
我认为您对这一行感到困惑:
this.numberOfClicks(this.numberOfClicks() + 1);
numberOfClicks
是一个可观察值,而不是一个数字,因此没有为它定义 +
。
当调用 numberOfClicks()
时,会将可观察对象“展开”为基础值(数字)。我相信将可观察对象作为具有单个参数的函数调用会更新值,因此 this.numberOfClicks(1+1)
会将 numberOfClicks
的值设置为 2。
关于javascript - Knockout.JS - 这个例子中的 observable 到底发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8304540/