Backbone 子视图和父视图不能同时工作

Backbone child view and parent view is not working simultaneously

我是 Backbone 的新手。当我尝试同时渲染父视图和子视图时,只渲染了父视图!我想知道为什么会这样,还有什么其他方法可以做到这一点?

childView.js:

var ChildView = Backbone.View.extend({
  template: _.template($('#foo').html()),
  initialize: function() {
  },
  render: function() {
    $(this.el).html(this.template({}));
    return this;
  }
});

parentView.js:

var ParentView = Backbone.View.extend({
  el: $('body'),
  initialize: function() {
    this.childView = new ChildView();
    this.render();
  },
  render: function() {
    var self = this;
    $.get('templates/parentView.html', function(data) {
      template = _.template(data, {});
      self.$el.html(template);
    }, 'html');
    $('#main').html(this.childView.render().el);
  },
});
var parentView = new ParentView();

parentView.html:

<header>
  <h1>This is header</h1>
</header>
<main id="main">

</main>
<footer>
  <p>This is footer</p>
</footer>

在父视图 render 函数中,子视图 el 被分配给 $('#main') 但到那时它不在 DOM 作为父视图 el 未附加到 DOM,您可以进行以下更改以将子视图 html 分配给父视图 el

this.$el.find('#main').html(this.childView.render().el);
$(body).html(this.$el); 

$("#main") 在 DOM 上搜索元素,this.$el.find("#main")this.$el 元素后代中搜索元素。

有很多可以改进的地方,这里有一些:

  • 不需要使用 jQuery 全局选择器,使用 this.$el for the view's element, or this.$() 进行范围 jQuery 搜索。
  • el 采用字符串或 DOM 元素,而不是 jQuery 对象。
  • render应该是幂等且快速的,不要每次都去取模板。
  • .html() 函数比 .empty().append().
  • 稍微重一点
  • 您可以将上下文传递给 .get()(成功)回调。
  • 如果要将视图分配给现有元素,请使用 .setElement()

子视图

var ChildView = Backbone.View.extend({
    template: _.template($('#foo').html()),
    render: function() {
        this.$el.empty().append(this.template({}));
        return this;
    }
});

父视图

var ParentView = Backbone.View.extend({
    el: 'body',
    initialize: function() {
        this.childView = new ChildView();

        $.get({
            url: 'templates/parentView.html',
            success: this.onTemplateLoad,
            context: this,
            dataType: 'html'
        });
    },
    render: function() {
        this.$el.empty().append(this.template({ /** data */ }));

        this.childView.setElement(this.$('#main'));

        return this;
    },

    onTemplateLoad: function(data) {
        this.template = _.template(data, {});
        this.render();
    }

});

实例化

var parentView = new ParentView();