I put my code into this jsFiddle here:
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');
});
Can somebody who has more experience than me with Knockout explain why the code is not resetting the two input textboxes, First Name and Last Name, after you click Add Person?
Note that I’m trying to reset them by calling this.NewPerson(pBlank) just after I’m done adding.
The reason your fields are persisting is because your pBlank object isn’t getting new observables (i.e. pBlanks fields are updating as you change them). http://jsfiddle.net/ngFM9/2/.
Here’s how I would do.
http://jsfiddle.net/ngFM9/1/ (I made quite a few changes)
HTML
JS