1

私はbackbone.jsの初心者です。

実は私はチャットアプリを開発しています。

メッセージを入力するためにユーザーにテキストエリアを与え、ユーザーが送信をクリックしたときに、そのメッセージを指定した上部の div に追加する必要があります。

backbone.jsを使用してこれをどのように達成できますか? テキストエリアと送信ボタンについては、以下のコードを参照してください。

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

chahistory ビューのコードの下を参照してください。

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

これは、あなたがとるべき方向性の単なる大雑把な例です。プロジェクトの構造に応じて、これに対して多くの改善を加えることができます。たとえば、1 つのメッセージを挿入するたびにページ全体を再描画しないようにします。メッセージを最後に追加するだけの価値があるかもしれません。

于 2013-08-20T09:15:36.837 に答える