1
votes

in the code below I'm using the element controller pattern to render a collection of products. The main view template is rendering correctly , I can see all the elements and the div selector "#cart-wrapper". Apparently when the main view call the nested view with "addOne" it's unable to find the above selector:

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);
    }
});

NESTED VIEW

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

Inside the addOne function the $("#cart-wrapper").length==0 . I did console.log(directory.cartItemView.el) and the underscore template seems ok with all the models rendered inside the table.

the main view is called like this :

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

1 Answers

1
votes

This is because you call $("#cart-wrapper") before adding root element of the view to your page, and that is where jQuery is looking for it. To fix it just call this.$("#cart-wrapper") instead.