javascript - 渲染 subview 时主干 View 中没有 $(this.el)

标签 javascript backbone.js

完整代码在这里... http://pastebin.com/EEnm8vi3

第 378 行没有将部分插入到当前 View 中。 剖面模型已正确传递到方法中。除插入子渲染 View 外,其他一切都按预期工作。

我想知道为什么 $(this.el) 是空的,因此不允许追加。尝试使用像 $('#sections') 这样的直接选择器也不起作用。

从上面的 pastbin 链接重复相关代码:(addOne 方法)

SCC.Views.SectionView = Backbone.View.extend({
    tagName: "div",
    className: "section",
    initialize: function(){
        _.bindAll(this, 'render');
        this.template = _.template($('#section-tmpl').html());
    },
    render: function() {
        console.log($(this.el));
        $(this.el).html(this.template(this.model.toJSON()));
        return this;
    }
});



SCC.Views.SectionsView = Backbone.View.extend({
    tagName: "div",
    id: "sections",
    className: "sections",
    initialize: function(){
        _.bindAll(this, 'render');
         //SCC.Sections.bind('add',   this.addOne, this);
         SCC.Sections.bind('reset', this.addAll, this);
         SCC.Sections.bind('all',   this.render, this);
    },
    render: function() {
        $(this.el).html("<p>rendered</p>");
        return this;
    },
    addOne: function(section) {
        var view = new SCC.Views.SectionView({model: section});
        $(this.el).append(view.render().el);
    },
    addAll: function() {
        this.collection.each(this.addOne);
    }

});



SCC.Sections = new SCC.Collections.Sections();
SCC.SectionsView = new SCC.Views.SectionsView({collection:SCC.Sections});
SCC.Sections.reset(window.SectionData);
$('#main').append(SCC.SectionsView.render().el);

最佳答案

我自己遇到了这个问题,所以我会把这个答案留给其他人:

当你像@lukemh 那样将 this.render 绑定(bind)到 'all' 时:

SCC.Sections.bind('all', this.render, this);

您实际上是在说每次在模型/集合中触发事件时重新渲染 View 。当您在 render 方法中使用 .html() 时,您还将覆盖所有可能已被 .append() 的 subview 通过 addOne 函数添加到它。

如果将 $(this.el).html() 调用移动到初始化 View ,问题就解决了。您仍然可以将渲染绑定(bind)到“全部”,但请确保您只重新渲染它的一部分,否则您将再次覆盖 subview 。

关于javascript - 渲染 subview 时主干 View 中没有 $(this.el),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7068770/

相关文章:

ajax - 主干抛出集合[方法]函数错误

backbone.js - 使用复杂的 JSON 创建 Backbone.js 模型

Javascript var 内部函数

javascript - 使用 jQuery 在对象中缓存选择器

javascript - 寄生构造函数模式与工厂模式在技术上有何不同

ruby-on-rails - 如何从另一个 Controller 内部获取 Controller 的响应?

javascript - 在 Backbone js View 中拥有静态变量

javascript - 理解 Javascript/Node 中闭包的变量捕获

javascript - 我将如何分隔字符串中的数字并使它们成为自己的值?

javascript - 如何在 Backbone 模型中放置按钮?