2013-08-20 19 views
1

我初學者Backbone.js的。如何從textarea的附加價值,使用Backbone.js的另一種觀點?

其實我開發的聊天應用程序。

我給textarea的用戶鍵入消息,並且我希望當上發送用戶點擊則該消息應該得到追加到我指定的上限刻度。

這可怎麼使用Backbone.js的得到實現? 請參見下面的代碼文本區域和提交按鈕:

<textarea name="message" cols="20" rows="4" id="usermessage" ></textarea> 
<input name="submitmessage" type="submit" id="submitmessage" value="Send" /> 

請參見下面的代碼chathistory觀點:

<div id="chatHistory"></div> 

我想要實現這個只使用Backbone.js的。請幫助....

window.ChatHistoryView = Backbone.View.extend({ 
initialize: function(){ 
     this.render(); 
    }, 
render: function(){ 
// Compile the template using underscore 
     var template = _.template($("#chat_History").html(), {}); 
     // Load the compiled HTML into the Backbone "el" 
     this.$el.html(template); 
    }, 
events: { 
    // "click input[type=button]": "doSearch" 
    }, 

}); 
    window.ChatInputView = Backbone.View.extend({ 
    initialize: function(){ 
    this.render(); 
}, 
render: function(){ 
    // Compile the template using underscore 
    var template = _.template($("#chat_Input").html(), {}); 
    // Load the compiled HTML into the Backbone "el" 
    this.$el.html(template); 
}, 
events: { 
    "click input[type=submit]": "updateChatHistory" 
}, 

updateChatHistory: function(event){ 
    this.chatHistoryView.$e1.append(); 
    app.navigate('', true); 
    window.history.back(); 
} 

請檢查並幫助我解決這個...

+0

你的骨幹代碼是什麼,或者你問我們爲你做? – AdityaSaxena

+0

只有骨幹,這是什麼意思?我想你想用jQuery來做到這一點,而不是主幹。創建主幹應用程序時,經常一起使用jQuery和主幹。 – Ringo

+0

@adityasaxena請參閱以下代碼: – user2139497

回答

0

有幾個方法可以做到這一點。最簡單的方法是在歷史視圖中公開一個接受方法並更新視圖的方法。

更新您的ChatHistoryView像這樣

messages : [], //this is a collection of messages the history view is showing 

//update your render method 
render: function(){ 
    var template = _.template(messageTpl, { messages : this.messages }); //note that message tpl is your raw template 
    // Load the compiled HTML into the Backbone "el" 
    this.$el.html(template); 
} 

addMessage : addMessage(message) { //message is an object 
    messages.push(message); 
    this.render(); 
} 

並更新ChatInputView像這樣

updateChatHistory: function(event){ 
    //construct an object 
    var message = { 
     text : this.$el.find('#usermessage').val() 
    }; 
    this.chatHistoryView.addMessage(message); //pass the message to the history view 

    // whatever other code you want that will do things 
    app.navigate('', true); 
    window.history.back(); 
} 

這是你應該考慮的方向只是一個粗糙的例子。根據項目的結構,您可以對此做出許多改進。一個例子是每次插入一條消息時不重繪整個頁面。可能只是爲了將消息追加到最後。