javascript - Knockout.JS - 这个例子中的 observable 到底发生了什么?

标签 javascript knockout.js

我目前正在尝试学习 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/

相关文章:

php - 最高效的客户对客户聊天系统

javascript - 控制程序生成方 block 的变异和衰减

javascript - 使用 javascript 加载 css 文件(通过使用 @import 而不是通过链接)

javascript - 使用 D3.JS 将 CSV 转换为 JSON

javascript - 如何在 ObservableArray 中将 '/' 替换为 '-' ? knockout js

javascript - 如何为复杂模型 knockout 进行数据绑定(bind)

javascript - Knockout JS 更新 observableArray 失败

javascript - knockout 和切换开关 - 数据绑定(bind)

javascript - 使用jquery将html操作为字符串并更新span内容

javascript - KnockoutJS 模板 'beforeRemove' 调用了 3 次而不是 1 次