私は自分のコードをこの 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 で私よりも経験のある人は、[人を追加] をクリックした後、コードが 2 つの入力テキスト ボックス、名と姓をリセットしない理由を説明できますか?
追加が完了した直後に this.NewPerson(pBlank) を呼び出して、それらをリセットしようとしていることに注意してください。