【问题标题】:Knockout JS click bindingKnockout JS 点击绑定
【发布时间】:2016-09-05 15:57:27
【问题描述】:

我不熟悉 Knockout JS,我正在他们的网站上练习同样的内容

Knockout Practice Home

所以,我面临的问题是我无法让点击绑定工作。

这是我的代码示例

查看 - HTML

<ul data-bind="foreach:friends">
    <li>
        <strong data-bind="text: friendName"></strong>
        <input type="checkbox" data-bind="checked: knowJS" />
        <input data-bind="value: favLib,visible: knowJS" />
    </li>
</ul>

<button data-bind="click: addFriend">Add Friend</button>

ViewModel - JavaScript

//Create a sample JS Class
function friend(name) {
    this.friendName = name;
    this.knowJS = ko.observable(false);
    this.favLib = ko.observable('');
};

// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
var AppViewModel= function(){
    this.friends = ko.observableArray([new friend("Chiranjib"), new friend("Nandy")]);
};

AppViewModel.addFriend= function(){
    this.friends.push(new friend("A new friend"));
};

// Activates knockout.js
ko.applyBindings(new AppViewModel());

这个 addFriend 点击事件没有被触发。我做错了什么?

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    问题是你的addFriend函数放错地方了,所以KO找不到。您已将其放在 AppViewModel 函数本身上,但您希望将其放在由该函数创建的对象上。

    实际上,您的浏览器正在告诉您问题所在。如果您打开 Web 控制台,您会看到:

    未捕获的引用错误:无法处理绑定“点击:函数(){return addFriend}” 消息:addFriend 未定义

    有两种方法可以将它放在对象上:将它放在将成为这些对象原型的对象上(可通过AppViewModel.prototype 访问),或者像使用friends 一样在构造函数中创建它。我看不出有什么不能分享的理由,所以我会去找原型:

    AppViewModel.prototype.addFriend= function(){
    // Note ----^^^^^^^^^^^
        this.friends.push(new friend("A new friend"));
    };
    

    具有这一变化的实时示例:

    //Create a sample JS Class
    function friend(name) {
        this.friendName = name;
        this.knowJS = ko.observable(false);
        this.favLib = ko.observable('');
    };
    
    // This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
    var AppViewModel= function(){
        this.friends = ko.observableArray([new friend("Chiranjib"), new friend("Nandy")]);
    };
    
    AppViewModel.prototype.addFriend= function(){
        this.friends.push(new friend("A new friend"));
    };
    
    // Activates knockout.js
    ko.applyBindings(new AppViewModel());
    <ul data-bind="foreach:friends">
        <li>
            <strong data-bind="text: friendName"></strong>
            <input type="checkbox" data-bind="checked: knowJS" />
            <input data-bind="value: favLib,visible: knowJS" />
        </li>
    </ul>
    
    <button data-bind="click: addFriend">Add Friend</button>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

    旁注:在 JavaScript 中,压倒性的约定是构造函数最初都是大写的,就像你的 AppViewModel 一样。所以friend函数应该是Friend。

    【讨论】:

    • 你是“老师”或“大师”。先生教师节快乐:)
    猜你喜欢
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 2014-02-21
    • 2017-11-18
    • 2013-10-24
    • 2016-02-19
    相关资源
    最近更新 更多