渲染方法中的子视图始终为null

时间:2017-02-21 23:54:38

标签: javascript backbone.js

当您在this.ImagesView中呼叫render时,为什么PostCreateView为空?

即使它已被初始化,它也始终为空。

PostCreateView = Backbone.View.extend({
    el: $('#create-product'),
    template: _.template(createTemplate),
    ImagesView: null,           
    initialize: function() {            
        this.ImagesView = new ImageViewCollection().render().el;
    },
    render: function() {
        this.$el.find('#images-collection').append(this.ImagesView)
    }
});

1 个答案:

答案 0 :(得分:-1)

this.ImagesView = new ImageViewCollection().render().el;是不好的惯例。

你应该做的是:

PostCreateView = Backbone.View.extend({
    el: $('#create-product'),
    template: _.template(createTemplate),
    ImagesView: null,           
    initialize: function() {            
        this.ImagesView = new ImageViewCollection()
    },
    render: function() {
        this.$el.find('#images-collection').append(this.ImagesView.render().el)
    }
});

更新

来自el

ImageViewCollection可能为空,因为您未在this方法中返回render。确保它执行此操作:

render: function(){
  // image view render logic
  return this
}
相关问题