knockout.js how to add and replace binding instance?
I have the following knockout.js code
I’ve got the following:
var itemLine = function() {
this.itemId = ko.observable();
this.itemType = ko.observable();
///this.otherFields = = ko.observable();....
};
var itemSet = function () {
this.items = ko.observableArray(_.map(initialData, function (item) {
var newItem = new itemLine();
newItem.itemId(item.itemId);
开发者_开发问答 newItem.itemType(item.itemType);
return newItem;
}));
this.current = new itemLine();
// works, but it req duplication of all my fields
this.add = function () {
var newItem = new itemLine();
newItem.itemId(this.current.itemId());
newItem.itemType(this.current.itemType());
this.items.push(newItem);
this.current.itemerId("");
this.current.itemType("");
};
// doesn't work
this.add = function () {
this.items.push(this.current);
this.current = new interviewLine(); // bindings are lost
};
What is wrong in the second add implementation? What's the correct way of doing this?
Currently, in your second add you are not actually updating the observables, just replacing them with new ones.
What I would do is make this.current an observable. Then in your second version of add you will set current to the new value like you would set any observable.
So, in your itemSet contructor you would initialize this.current like:
this.current = ko.observable(new itemLine());
Then, in your second add function, set this.current like:
this.current(new interviewLine());
Something like this: http://jsfiddle.net/rniemeyer/j72NU/
Is this close to what you are trying to do?
精彩评论