1

我有一个已经呈现帖子集合的视图:

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

1 回答 1

2

这里绝对没有问题,因为模板无论如何都不是 Backbone 结构的一部分。我只有一个说法,那就是你应该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);
于 2013-04-22T08:53:01.287 回答