以相同的形式添加和编辑

时间:2013-10-06 08:41:27

标签: c# asp.net-mvc knockout.js

我需要创建一个以相同形式添加和编辑的应用程序。我实现了这个例子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 }

]));

1 个答案:

答案 0 :(得分:1)

添加添加新项目的按钮

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

并将其连接到viewmodel中的此功能

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

编辑:添加到你的小提琴,使用添加