2016-02-10 62 views
0

我想在observableArray中添加元素,但在這裏我有新增元素替換最後一個元素的問題。在陣列中添加動態元素使用淘汰賽

var bugTracker = function() { 
    var self = this; 
    self.bugName = ko.observable(''), 
    self.bugList = ko.observableArray([ 
     {name:"Abc",age:27},{name:"Dooo",age:27},{name:"Usss",age:27},{name:"Yeess",age:27} 
    ]) 
    self.addBug = function() { 
    var newBug = { 
     name: self.bugName, 
     age: 86 
    } 
    self.bugList.push({ 
     name: self.bugName, 
     age: 89 
    }); 
    } 
    self.removeBug = function() { 
    self.bugList.remove(this); 
    } 
} 
bugTracker.bugList 
$(function() { 
    ko.applyBindings(new bugTracker()); 
}); 

HTML:

<input type="text" data-bind="value : bugName" > 
<input type="button" data-bind="click: addBug" value="Add Bug"/> 
<ol data-bind="foreach : bugList"> 
    <li data-bind="text : name" > 
    </li> 
</ol> 

輸出:

enter image description here

回答

1

您需要調用bugName作爲一個函數來獲取當前值,則可以放棄的newBug雙創作,所以:

self.addBug = function() { 
    var newBug = { 
    name: self.bugName(), 
    age: 86 
    } 
    self.bugList.push(newBug); 
} 

請參閱this working jsfiddle

+0

**非常感謝。 ** –