主干嵌套视图找不到 id 选择器

Backbone nested view unable to find id selector

本文关键字:id 选择器 找不到 视图 嵌套      更新时间:2023-09-26

在下面的代码中,我使用元素控制器模式来呈现产品集合。主视图模板渲染正确,我可以看到所有元素和div 选择器"#cart 包装器"。显然,当主视图使用"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);

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