fiskah
fiskah

Reputation: 5902

Backbone.js event not fired

I have the following backbone.js code, which is meant to render a product list provided by the backend. The problem is that the render method of AppView is never called - i.e. the listener attached via this.listenTo(product_list, 'change', this.render); is not fired when the fetch call is done.

Can anyone tell me what is wrong?

$(function(){

    Product = Backbone.Model.extend({
        url: '/api/product',
        defaults: {
            name: 'default name'
        }
    });

    // Collection
    ProductList = Backbone.Collection.extend({
        url: '/api/products',
        model: Product,
    });
    product_list = new ProductList();

    // Views
    ProductListView = Backbone.View.extend({
        tagName: 'div',
        initialize: function(){
            this.listenTo(this.model, 'change', this.render);
        },
        render: function(){
            console.log('p:render');
            this.$el.html('<input type="checkbox" value="1" name="' + this.model.get('title') + '" /> ' + this.model.get('title') + '<span>$' + this.model.get('price') + '</span>');
            this.$('input').prop('checked', this.model.get('checked'));

            return this;
        }
    });
    AppView = Backbone.View.extend({
        el: '#list',
        initialize: function(){
            this.list = $('#list');
            this.listenTo(product_list, 'change', this.render);

            product_list.fetch({reset:true});
            console.log('fetch');
        },
        render: function(r) {
            console.log('AppView.render');
            product_list.each(function(product){
                console.log('p:e:render()');
                var view = new ProductListView({ model: product });
                this.list.append(view.render().el);
            });
            return this;
        }
    });

    new AppView();
});

Upvotes: 1

Views: 64

Answers (1)

Ryan Lynch
Ryan Lynch

Reputation: 7776

I had this same issue, and I discovered by looking at the source that collections don't fire a change event when they fetch. The change event is only fired on models that have been updated. Since you are fetching with reset:true, try listening for the reset event.

Upvotes: 3

Related Questions