我正在尝试向我的Knockout observableArray
添加“默认”对象。我的代码当前的方式,我最终添加完全相同的对象到数组而不是对象的新实例。我尝试使用jQuery的.extend()
,但是,这没有用,所以我正在寻找输入。
以下是展示我的问题的演示:http://jsfiddle.net/2c8Fx/
HTML :
<div data-bind="foreach: People">
<input type="text" data-bind="value: Name" />
</div>
<button type="button" data-bind="click: AddPerson">Add Person</button>
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
脚本:
function ViewModel() {
var self = this;
self.EmptyPerson = ko.mapping.fromJS({Name: null, Age: null});
self.People = ko.observableArray([self.EmptyPerson]);
self.AddPerson = function() {
self.People.push(self.EmptyPerson);
};
}
ko.applyBindings(new ViewModel());
这不起作用,因为observableArray
实际上是为每个索引保存对同一对象的引用。
创建Knockout对象的新实例的最佳方法是什么?
答案 0 :(得分:2)
function ViewModel() {
var self = this;
self.People = ko.observableArray();
self.AddPerson = function() {
self.People.push(ko.mapping.fromJS({Name: null, Age: null}));
};
}
ko.applyBindings(new ViewModel());
我这样做了,它的效果就像你认为的那样。我希望这会有所帮助。
查看一个有效的例子here