Knockout JS对象原型问题

时间:2016-09-05 15:44:13

标签: javascript knockout.js

这不是一个错误,但我无法弄清楚发生了什么。

我想在页面加载时显示一组朋友。然后,当点击Add Friend按钮时,

它应该添加名为SpaceX的新朋友。那就发生了。

但我无法弄清楚为什么它会在负载中列出名为SpaceX的朋友。

这是代码段。

查看-HTML

<!-- This is a *view* - HTML markup that defines the appearance of your UI -->

<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" />
        <button data-bind="click: removeFriend">X</button>
    </li>
</ul>

<button data-bind="click: addFriend('SpaceX')">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.removeFriend = function() {
        obj.friends.remove(this);
    };
};

// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI

//Create an object type using constructor function
function AppViewModel(){
    this.friends = ko.observableArray([new Friend("Chiranjib"), new Friend("Nandy")]);
};

//Add a property to the prototype of the object type
AppViewModel.prototype.addFriend= function(fname){
    this.friends.push(new Friend(fname));
};

//Create a specific object out of the object type defined
var obj = new AppViewModel();

// Activates knockout.js
ko.applyBindings(obj);

页面加载的输出类似于

enter image description here

但只有在点击SpaceX按钮时才会添加Add Freind。我做错了什么?

1 个答案:

答案 0 :(得分:1)

问题在于您的数据绑定。在数据绑定步骤中遇到淘汰时:

data-bind="click: addFriend('SpaceX')"

它将立即运行 并将函数的结果分配给click事件处理程序。如果需要以这种方式将参数传递给绑定函数,则需要将其包装在另一个函数中:

data-bind="click: function() { addFriend('SpaceX'); }"

然后,此匿名函数将绑定到click事件,并且在您实际点击按钮之前不会调用addFriend

相关问题