2013-04-22 85 views
1

我有一個觀點,即已經被渲染的帖子集:呈現Backbone.js的不同的模板在相同的看法

Social.Views.StreamsIndex = Backbone.View.extend({ 

    template: JST['streams/index'], 

    render: function(){ 
    $(this.el).html(this.template({ 
     entries: this.collection.toJSON() 
    })); 
    return this; 
    } 
}); 

現在我有一個職位,我要呈現不同的評論模板評論:

Social.Views.StreamsIndex = Backbone.View.extend({ 

    template: JST['streams/index'], 
    events: { 
    'submit .comment_submit': 'comment_create' 
    }, 
    comment_create: function(event) { 
    //create comment code 

創造我想要做這樣的事情,這樣纔可以使註釋模板後

$("#comment).html(this.template1({ 
     comment: comment 
    })); 
    } 
}); 

是否可以從同一視圖呈現兩個模板?

編輯:(添加視圖)

Social.Views.StreamsIndex = Backbone.View.extend({ 

template: JST['streams/index'], 
template1: JST['streams/comment'], 

events: { 
    'submit .comment_submit': 'comment_create' 
}, 

initialize: function(){ 
    this.collection.on('reset', this.render, this); 
    this.model = new Social.Models.StreamsIndex(); 
    this.model.bind('comment_createSuccess', this.comment_createSuccess); 
}, 

render: function(){ 
    $(this.el).html(this.template({ 
     entries: this.collection.toJSON() 
    })); 
    return this; 
}, 

comment_create: function(event) { 
    event.preventDefault(); 
    event.stopPropagation(); 
    post_id = $(event.currentTarget).attr("data-post-id"); 
    href = $(event.currentTarget).attr('action'); 
    comment_text = $("#comment_txt_"+post_id).val(); 
    this.model.create_comment(href, post_id, comment_text); // this sends ajax request and post the comment to server 
}, 

comment_createSuccess: function(data, post_id) { 
    this.$("#comment_for_post_"+post_id).append(this.template1({ 
     comment: data 
    })); 
} 
}); 

回答

2

這裏絕對沒有問題,因爲模板是反正不是骨幹結構的一部分。我只有一句話,那就是你應該在視圖中使用this.$(這是this.$el.find的快捷鍵,所以你只能找到你視圖的el的後代)。

所以......

this.$('#comment').append(this.template1({ // changed to append to be used several times 
    comment: comment 
})); 

編輯:
關於你的背景問題:

this.model.bind('comment_createSuccess', this.comment_createSuccess); 

在這裏,您可以使用bind的第三個參數設置回調的背景下:

this.model.bind('comment_createSuccess', this.comment_createSuccess, this); 

this您的回調(comment_createSuccess)現在將成爲您的觀點。
我個人寧可使用Events#listenTo將自動綁定上下文:

this.listenTo(this.model, 'comment_createSuccess', this.comment_createSuccess); 
+0

酷。當我嘗試我得到這個錯誤:「這個。$不是一個函數」。我錯過了什麼? – 2013-04-22 09:05:59

+1

@Srikanth張貼您的整個看法,你可能有一個上下文問題([源](http://backbonejs.org/#View-dollar))。 – Loamhoof 2013-04-22 09:12:36

+0

我已編輯我的問題與查看 – 2013-04-22 09:17:41