【问题标题】:Backbone nested view unable to find id selector主干嵌套视图找不到 id 选择器
【发布时间】:2013-09-15 10:58:31
【问题描述】:

在下面的代码中,我使用元素控制器模式来呈现产品集合。主视图模板渲染正确,我可以看到所有元素和 div 选择器“#cart-wrapper”。显然,当主视图使用“addOne”调用嵌套视图时,它无法找到上述选择器:

directory.CartView = Backbone.View.extend({
    initialize: function(options) { 
        this.collection = directory.shellView.cartcollection;
    },

    render: function(){
        this.$el.html(this.template());
        this.addAll();
        return this;
    },

    addAll: function() { 
        this.collection.each(this.addOne, this);
    },

    addOne: function(model) {
        directory.cartItemView = new directory.CartItemView({model: model}); 
        directory.cartItemView.render();
        $("#cart-wrapper").append(directory.cartItemView.el);
    }
});

嵌套视图

directory.CartItemView = Backbone.View.extend({
    render: function(){
        this.$el.html(this.template(this.model.toJSON()));
        return this;
   }
});

在 addOne 函数中 $("#cart-wrapper").length==0 。 我做了 console.log(directory.cartItemView.el) 并且下划线模板似乎可以与表格内呈现的所有模型一起使用。

主视图是这样调用的:

 directory.cartView = new directory.CartView();
 directory.cartView.render();   
 $("#content").html(directory.cartView.el);

【问题讨论】:

    标签: javascript jquery backbone.js


    【解决方案1】:

    这是因为您在将视图的根元素添加到页面之前调用了$("#cart-wrapper"),而这正是jQuery 正在寻找它的地方。要修复它,只需调用 this.$("#cart-wrapper")

    【讨论】:

      猜你喜欢
      • 2013-05-14
      • 2015-04-26
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      相关资源
      最近更新 更多