2013-04-22 88 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