2013-08-22 168 views
2

我在淘汰賽js中遇到了一個問題,找不到任何解決方案,我有一個對象列表,我將它放在一個可觀察數組中,並將它們顯示在一個表中,單擊一行,將對象屬性填充到適當的字段中。點擊更新可觀察

當任何字段數據更新時,它立即反映在表中,但我希望比單擊Save按鈕時要比表中的數據必須更新,以便我還可以通過ajax更新數據庫中的數據。 一個簡單的小提琴在創建:jsfiddle

的Javascript是:

var myData = [{'Id':1,'UserName':'Imran',Active:true},{'Id':2,'UserName':'Khan',Active:false},{'Id':3,'UserName':'Balouch',Active:true}]; 
function User(id,name,active) 
{ 
    this.Id = ko.observable(id); 
    this.UserName = ko.observable(name); 
    this.Active = ko.observable(active); 
} 
var viewModel = function() { 
    var self = this; 

    self.AllUsers = ko.observableArray([]); 
    self.CurrentUser = ko.observable(new User(-1,'',false)); 

    var mappedUsers = $.map(myData, function (item) { 
     return new User(item.Id, item.UserName, item.Active); 
    }); 

    self.AllUsers(mappedUsers); 

    self.GetUser = function(item) 
    { 
     ko.utils.arrayForEach(self.AllUsers(), function (mainItem) { 
      if (item.Id == mainItem.Id) 
       self.CurrentUser(mainItem); 
     }); 
    }; 

    // I want this function to update the table and also send Ajax call. 
    self.UpdateRecord = function() 
    { 
     //ko.utils.arrayForEach(self.AllUsers(), function (mainItem) { 
     // if (self.CurrentUser().Id() == mainItem.Id()) 
     //  mainItem.UserName = self.CurrentUser().UserName(); 
     //}); 
    }; 
}; 
$(function() { 
     ko.applyBindings(new viewModel()); 
    }); 

和HTML是:

<table style="width:100%;"> 
<tbody data-bind="foreach:AllUsers"> 
    <tr data-bind="click:$root.GetUser"> 
     <td data-bind="text:Id"></td> 
     <td data-bind="text:UserName"></td> 
     <td data-bind="text:Active"></td> 
    </tr> 
</tbody> 
</table> 
<br/> 
<input type="text" data-bind="value:CurrentUser().UserName"/> 
<br/> 
<button data-bind="click:UpdateRecord">Save</button> 

任何幫助將不勝感激,謝謝提前

+2

你應該閱讀這些文章:http://www.knockmeout.net/2011/03/guard-your-model-accept-or-cancel-edits.html和http://www.knockmeout.net/2013/01/simple-editor-pattern-knockout-js.html – nemesv

+0

@nemesv非常感謝鏈接,我已經通過第一個鏈接,但無法找到第二個在我的搜索中,我正在經歷它,我覺得它會解決我的問題。 –

回答

2

更改:
mainItem.UserName = 'ABC';
通過:
mainItem.UserName('ABC');

的jsfiddle:http://jsfiddle.net/R5yNM/5/

+0

儘管我通過nemesv提供的第二個鏈接解決了問題,但仍然如您的答案正在解決我的問題,因此將其標記爲答案。 –