2013-10-06 16 views
0

我需要創建一個應用程序,以相同的形式添加和編輯。我實現了這個例子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 } 

]));

+0

我沒有看到你想添加的地方。你所需要做的就是myObservableArrayName.push(item)。 – segFault

+0

是的正確我只是需要添加.push(項目),但我想添加它在我做一個編輯相同的形式..如果我添加一個方法addItem我仍然需要通過itemForEditing,以便我的表單將可見。 –

回答

1

添加一個按鈕,添加一個新的項目

<button data-bind="click: addItem"> Add new item </button> 

並將其連接到這個功能在您的視圖模型

var self = this; 
self.addItem = addNewItem; 
function addNewItem() { 
    var newItem = new Item(); 
    newItem.name = 'new item'; 
    self.items.push(newItem); 
} 

編輯:其添加到您不甘示弱,與工作增添

+0

http://jsfiddle.net/rmindel/K3gJT/110/ –

+0

你的例子很棒,但我需要的是,當我點擊添加新項目按鈕時,窗體將出現在他編輯的相同表單中,並且他將以相同的形式添加 –

+0

你可以在添加到列表後點擊這個新項目以在編輯表格中打開它 –

相關問題