我需要創建一個應用程序,以相同的形式添加和編輯。我實現了這個例子http://jsfiddle.net/rniemeyer/K3gJT/。我嘗試更改代碼來實現添加,但我堅持這一點。以相同的格式添加和編輯
var Item = function(data) {
this.name = ko.observable();
this.price = ko.observable();
//populate our model with the initial data
if(data != null) {
this.update(data);
}
};
//can pass fresh data to this function at anytime to apply updates or revert to a prior version
Item.prototype.update = function(data) {
this.name(data.name || "new item");
this.price(data.price || 0);
};
var ViewModel = function(items) {
//turn the raw items into Item objects
this.items = ko.observableArray(ko.utils.arrayMap(items, function(data) {
return new Item(data);
}));
//hold the currently selected item
this.selectedItem = ko.observable();
//make edits to a copy
this.itemForEditing = ko.observable();
this.Add = ko.observable();
this.selectItem = this.selectItem.bind(this);
this.acceptItem = this.acceptItem.bind(this);
this.revertItem = this.revertItem.bind(this);
};
ko.utils.extend(ViewModel.prototype, {
//select an item and make a copy of it for editing
selectItem: function(item) {
this.selectedItem(item);
this.itemForEditing(new Item(ko.toJS(item)));
},
acceptItem: function(item) {
var selected = this.selectedItem(),
edited = ko.toJS(this.itemForEditing()); //clean copy of edited
//apply updates from the edited item to the selected item
selected.update(edited);
//clear selected item
this.selectedItem(null);
this.itemForEditing(null);
},
//just throw away the edited item and clear the selected observables
revertItem: function() {
this.selectedItem(null);
this.itemForEditing(null);
}
});
ko.applyBindings(new ViewModel([
{ name: "Cheese", price: 2.50 },
{ name: "Pepperoni", price: 3.25 },
{ name: "Deluxe", price: 4.25 }
]));
我沒有看到你想添加的地方。你所需要做的就是myObservableArrayName.push(item)。 – segFault
是的正確我只是需要添加.push(項目),但我想添加它在我做一個編輯相同的形式..如果我添加一個方法addItem我仍然需要通過itemForEditing,以便我的表單將可見。 –