1

我是backbone.js 的初学者。

实际上我正在开发聊天应用程序。

我将 textarea 给用户以输入消息,并且我希望当用户单击发送时,该消息应附加到我指定的上部 div。

使用backbone.js如何实现这一点?请参阅下面的 textarea 代码和提交按钮:

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

请参阅以下代码以获取聊天历史视图:

<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();
}

请检查并帮助我解决这个问题...

4

1 回答 1

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();
}

这只是您应该采取的方向的粗略示例。根据项目的结构,您可以对此进行许多改进。例如,每次插入一条消息时不要重绘整个页面。将消息附加到末尾可能是值得的。

于 2013-08-20T09:15:36.837 回答