2013-06-19 41 views
1

我有一个像这样的ko maaaped数组。按钮单击保存在KO

var Type = [];   
     Type.push("Flip"); 
     Type.push("Bar"); 
     Type.push("Foo"); 

     // converting the json to ko mapped collection 
     viewModel = { 
      firstValue: ko.observable("hello"), 
      Type: ko.mapping.fromJS(Type), 
      save: function() { 
       alert(viewModel.Type[0]); 
       alert("have to save the values here"); 
      }, 

     }; 

我用foreach来创建一个输入来编辑该数组。

<div data-bind="foreach: Type"> 
<p><input data-bind='value: $parent.Type()[$index()]' /></p> 

<button data-bind='click: save'> Save </button> 

我想保存编辑后的值回按钮点击阵列,,而不是保存该instantlly。如何实现这一目标?

http://jsfiddle.net/mS6LF/1/

回答

2

您需要将输入绑定到一个临时副本而不是实际的数据,然后保存你的临时数据复制到实际值。

这里的和更新的小提琴表示方法:http://jsfiddle.net/mS6LF/8/

var Type = []; 
Type.push({ value: "Flip", temp: "Flip"}); 
Type.push({ value: "Bar", temp: "Bar"}); 
Type.push({ value: "Foo", temp: "Foo"}); 

// converting the json to ko mapped collection 
viewModel = { 
    firstValue: ko.observable("hello"), 
    Type: ko.mapping.fromJS(Type), 
    save: function() {   
     // Loop through array and set all temp values to the actual value. 
     ko.utils.arrayForEach(this.Type(), function(element){ 
      element.value(element.temp()); 
     }); 
    }, 

}; 

ko.applyBindings(viewModel); 

数组现在持有与实际值和模仿对象。我们将输入绑定到副本而不是实际的数据。

<div data-bind="foreach: Type"> 
    <p> 
     <input data-bind='value: temp' /> 
     Actual = <span data-bind='text: value'></span> 
    </p> 
</div> 
<button data-bind='click: save'>Save</button> 

对于更复杂的方法,see Ryan Niemeyer's protectedObservable blog post

+0

很好的答案..我已经根据你提到的精彩文章更新了你的例子。请在 –

0

我更新geoff-appleford例如基于在前面的回答

提供Ryan Niemeyer's protectedObservable修改无需添加或复制您的阵列中的每个值与original-valuetemp-value。您只需确保您的可观察物品是protectedObservable
请检查我的示例DEMO

+0

以下更新我的小提琴示例 –