0

I have defined a view bind to a collection.

1) when I initialise the View, a fetch call on collection is performed.
2) If I look to the result of the get request it is ok
3) The I would like to trigger this change (in myCollection) for calling the render function but it does not work.

Here is part of my code:

define([
    "MyCollection",
    "!text/template"
], function (myCollection, myTemplate) {

    var myView = Backbone.View.extend({

        initialize: function ()
        {
            myCollection.bind('change', this.render); // why the render is not called when 
                                                      // I perform the fetch even if the data is correctly loaded? 

            myCollection.fetch(); // it works
        },

        render: function ()
        {
            // some code
            this.$el <-- undefined 
        }

    });

    return myView;
});

If I use

1)

   initialize: function ()
   {
       myCollection.bind('reset', this.render);  // this.$el <-- undefined in render call, Why?

        myCollection.fetch(); // it works
   }

2)

myCollection.fetch({
    success: function () {
         that.render(); // <-- here the $el is defined and it works, Why myCollection.bind('reset', this.render); not?? 
         // it seems to me that when I use reset the render function is called before the this.$el is defined
    }
});
underscore666
  • 1,719
  • 4
  • 24
  • 37

2 Answers2

1

You have to listen to the reset event, not the change event.

so:

myCollection.bind('reset', this.render, this);
Vincent Briglia
  • 3,068
  • 17
  • 13
  • If I change in reset I get the following message: `Uncaught TypeError: Cannot call method 'html' of undefined`. more details in my questions – underscore666 May 15 '12 at 22:16
1

Backbone triggers a "reset" event, not a change event on the successful completion of a fetch()

var myView = Backbone.View.extend({

    initialize: function ()
    {
        myCollection.bind('reset', this.render);
        myCollection.fetch(); // it works
    },

    render: function ()
    {
        // some code
    }

});
Edward M Smith
  • 10,627
  • 2
  • 46
  • 50