2015-12-10 45 views
1

我需要創建一個簡單的評論框(就像facebook評論的例子)蒙山js。我是新來的KO,我試圖搜索,但我似乎無法找到這個愚蠢的問題的答案。我會花更多的時間,但我需要快速完成我的作業。因此,這是我的HTML:如何從輸入字段獲取值並將其分配給視圖模型中的JavaScript對象?

<div id="comment-input-container"> 
    <input type="text" placeholder="comment..." data-bind="value: commentText"> 
    <button type="submit" data-bind="click: addComment">Add comment</button> 
</div> <!-- From this input I need to take the commentText and use it in the addComment function --> 
<hr> 

<!-- Knockout Template for showing comments --> 
<div id="comment-box" data-bind="foreach: comments"> 
    <p data-bind="text: fullName"></p> 
    <p data-bind="text: datePosted"></p> 
    <div class="commentBody"> 
     <div class="commentContent"> 
      <div class="commentText" data-bind="text: commentText"></div> 
      <div class="commentButtonsBox"></div> 
     </div> 
    </div> 
</div> 

這裏是JS:

function CommentsViewModel() { 
    var self = this; 

    self.comments = ko.observableArray([{ 
     fullName: "Todor Atanasov", 
     datePosted: new Date(), 
     commentText: "Awesome vid guys ty."} 
    ]); 

    self.addComment = function() { 
     self.comments.push({ 
      fullName: "new guy", 
      datePosted: new Date(), 
      commentText: "new comment" 
     }) 
    } 
} 

ko.applyBindings(new CommentsViewModel()); 

所以,我應該在commentText的地方寫上: 「新評論」

+1

請參閱[「應該在其標題中包含」標籤?「](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles),其中共識是「不,他們不應該」! –

回答

1

試試這個:

function CommentsViewModel() { 
    var self = this; 

    self.newComment = ko.observable(); //add this 

    self.comments = ko.observableArray([{ 
     fullName: "Todor Atanasov", 
     datePosted: new Date(), 
     commentText: "Awesome vid guys ty."} 
    ]); 

    self.addComment = function() { 
     self.comments.push({ 
      fullName: "new guy", 
      datePosted: new Date(), 
      commentText: self.newComment() 
     }) 
    } 
} 

ko.applyBindings(new CommentsViewModel()); 

替換下列html代碼:

<input type="text" placeholder="comment..." data-bind="value: newComment " /> 
相關問題