2012-06-15 102 views
0

下面是相關的代碼綁定到單獨的文本框:淘汰賽:數據在foreach結合

<div data-bind="foreach: chats, visible: chats().length > 0"> 
    <input data-bind='value: $parent.newCommentText' /> 
    <a href="#" data-bind='click: $root.addComment'>Add comment</a> 
</div> 

視圖模型:

self.newCommentText = ko.observable() 
self.addComment = function(chat) { 
      var newComment = { CourseItemDescription: self.newCommentText(), }; 
      chat.CommentList.push(newComment); 
      self.newCommentText(""); 
      $.ajax({ 
       url: "@Url.Action("AddComment")", 
       data: ko.toJSON(newComment), 
       type: "post", 
       contentType: "application/json" 
      }); 
     }; 

的問題是,這將使不管我在一個文本框中鍵入在所有其他文本框中。我怎樣才能做到這一點,以便它只綁定到用戶輸入的文本框,並將該數據提供給addComment函數?

回答

1

如果您希望每個聊天都能夠添加自己的評論字段,那麼您希望將您的newCommentText字段添加到chat對象而不是父級。然後,您可以讀取它並將其清除掉傳遞至addCommentchat對象。

0

我需要把newCommentText放在聊天數組中。

所以代碼將成爲

self.addComment = function(chat) { 
      var newComment = { CourseItemDescription: chat.newCommentText(), }; 
      chat.CommentList.push(newComment); 
      chat.newCommentText(""); 
      ... 
     };