【问题标题】:Render a different template in backbone.js in same view在同一视图中在主干.js 中呈现不同的模板
【发布时间】:2013-04-15 02:25:18
【问题描述】:

我有一个已经在渲染帖子集合的视图:

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

【问题讨论】:

    标签: ruby-on-rails backbone.js backbone-views


    【解决方案1】:

    这里绝对没有问题,因为模板无论如何都不是 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);
    

    您的回调 (comment_createSuccess) 中的this 现在将成为您的视图。
    我个人更愿意使用Events#listenTo 来自动绑定上下文:

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

    【讨论】:

    • 酷。当我尝试时出现此错误:“this.$ 不是函数”。我错过了什么吗?
    • @Srikanth 发布您的整个视图,您可能遇到上下文问题 (source)。
    • 我已经用 View 编辑了我的问题
    • 太棒了!非常感谢您的帮助。我做了这个“this.listenTo(this.model, 'comment_createSuccess', this.comment_createSuccess)”,它就像一个魅力。
    猜你喜欢
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    相关资源
    最近更新 更多