我目前正在尝试学习QuintOut.js-我对JavaScript本身也相对较新。

网站上有一个示例 - http://knockoutjs.com/examples/clickcounter.html - 我目前正在试图缠绕我的头。

我在下面的代码中发表了一些评论,并以我的想法进行了评论。那里有一个问题,即该功能如何工作。

如果某人在淘汰赛中经验丰富的人可以准确解释那里发生了什么,那就太好了。谢谢。

 (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。

其他提示

this.numberOfClicks; 是可观察的。这是一个特殊的敲除,可以使您可以双向绑定到DOM元素。每当更改此属性时,任何绑定到其的DOM元素都会自动更新其值。

您可以访问并设置可观察到的功能,因为它们实际上是封面下的功能。

clickCounterViewModel.numberOfClicks(99);
var numClicksInViewModel = clickCounterViewModel.numberOfClicks(99);
//numClicksInViewModel == 99

this.hasClickedTooManyTimes 是一个 dependentObservable, ,这类似于可观察的,除了它是一个函数。像常规观察物一样,这些也可以与DOM元素绑定。什么时候 hasClickedTooManyTimes 被执行,淘汰赛将保持跟踪(在封面上)的追踪,以便于其所依赖的观察值 他们 更改,绑定系统将知道以更新任何绑定到的内容 hasClickedTooManyTimes

因此,对于这个特定示例:

this.hasClickedTooManyTimes = ko.dependentObservable(function () {
    return this.numberOfClicks() >= 3;
}, this);

每当 numberOfClicks 更新,任何内容都可以 hasClickedTooManyTimes 将要 自动地 自我更新。

然后 this 您传递给依赖性观用功能的参数只是句法糖 this 表现正常。

这是 很棒的视频 首先向我介绍了淘汰赛

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top