Knockout JS点击绑定

时间:2016-09-05 07:39:24

标签: javascript knockout.js

我不知道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点击事件未被触发。我做错了什么?

1 个答案:

答案 0 :(得分:2)

问题是您的addFriend功能位于错误的位置,因此KO无法找到它。您已将其放在AppViewModel函数本身上,但您希望它位于由函数创建的对象上。

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

Uncaught ReferenceError: Unable to process binding "click: function (){return addFriend }"
Message: addFriend is not defined

将它放在对象上的两种方法:将它放在将成为这些对象原型的对象上(可通过AppViewModel.prototype访问),或者在构造函数中创建它,就像使用{{1 }}。我没有看到任何可以分享的理由,所以我去寻找原型:

friends

带有这一改变的实例:

&#13;
&#13;
AppViewModel.prototype.addFriend= function(){
// Note ----^^^^^^^^^^^
    this.friends.push(new friend("A new friend"));
};
&#13;
//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());
&#13;
&#13;
&#13;

旁注:在JavaScript中,压倒性的约定是构造函数最初像你的<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>一样大写。因此AppViewModel函数应为friend