我把我的代码放到这个 jsFiddle 里:http: //jsfiddle.net/damianofusco/ngFM9/
function Person(data) {
this.Id = data.Id;
this.FirstName = ko.observable(data.FirstName);
this.LastName = ko.observable(data.LastName);
this.FriendlyName = ko.computed(function() {
return this.Id + ' ' + this.FirstName() + ' ' + this.LastName();
}, this);
this.HasValues = ko.computed(function() {
return this.FirstName().length > 0 && this.LastName().length > 0;
}, this);
}
var pBlank = new Person({
Id: 0,
FirstName: "",
LastName: ""
});
var p1 = new Person({
Id: 1,
FirstName: "Damiano",
LastName: "Fusco"
});
var p2 = new Person({
Id: 2,
FirstName: "John",
LastName: "Doe"
});
window.myVM = {
People: ko.observableArray([p1, p2]),
NewPerson: ko.observable(pBlank),
AddPerson: function() {
var newid = this.People().length + 1;
var newItem = new Person({
Id: newid,
FirstName: this.NewPerson().FirstName(),
LastName: this.NewPerson().LastName()
});
console.log(newItem.FriendlyName());
this.People.push(newItem);
this.NewPerson(pBlank);
}
};
window.myVM.People.subscribe(function() {
console.log('People changed');
});
window.myVM.NewPerson.subscribe(function() {
console.log('NewPerson changed');
});
window.myVM.NewPerson().FirstName.subscribe(function() {
console.log('NewPerson.FirstName changed');
});
在 Knockout 方面比我有更多经验的人可以解释为什么在单击“添加人员”后代码没有重置两个输入文本框,名字和姓氏?
请注意,我正在尝试通过在完成添加后调用 this.NewPerson(pBlank) 来重置它们。