[英]Knockout JS object prototype issue
這不是錯誤,但我不知道發生了什么。
我想在頁面加載時顯示一組特定的朋友。 然后,當點擊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);
頁面加載時的輸出看起來像
但SpaceX
的時候應該只添加Add Freind
按鈕被點擊。 我究竟做錯了什么 ?
問題出在您的數據綁定中。 當在數據綁定步驟中遇到敲除時:
data-bind="click: addFriend('SpaceX')"
它將立即運行它,並將函數結果分配給click
事件處理程序。 如果需要以這種方式將參數傳遞給綁定函數,則需要將其包裝在另一個函數中:
data-bind="click: function() { addFriend('SpaceX'); }"
然后,該匿名函數將綁定到click
事件,直到您真正單擊按鈕,才調用addFriend
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.