Question

I have a Backbone collection which keeps requesting data from the RESTful API. What I do is loading the view with the router, in the view it calls the model (in initialize) and the model will do the collection fetch.

I make use of require.js in the router.

Here are the scripts, can you see what is causing this loop and how to fix this?

Thanks in advance!

In the router:

goToUsers: function() {

    require(['./models/users', './views/users_view', './collections/user_collection'], function(UsersMdl, UsersView, UsersCollection) {

        OF.usersView = new OF.UsersView;
        OF.usersView.render();

    });

}, 

In the View:

initialize: function() {

    //set the new address variable.
    OF.usersMdl = OF.usersMdl || new OF.UsersMdl();

},

In the Model:

initialize: function() {

    //on change functions can be done here

    //OF.usersCollection = new OF.UsersCollection;
    OF.usersCollection = new OF.UsersCollection;
    OF.UsersCollection.fetch({ data: { "admin": OF.login.attributes.admin, "session": OF.login.attributes.session } });

},

The Collection:

OF.UsersCollection = Backbone.Collection.extend({

    initialize: function() {
        console.log("People Collection is initialized");
    },

    url: 'php/api/users',

    model: OF.UsersMdl

});
Was it helpful?

Solution

When

OF.UsersCollection.fetch({ data: { "admin": OF.login.attributes.admin, "session":     OF.login.attributes.session } }) 

is executed. It initialize new model objects which do the fetch of collection again.

initialize: function() {
//OF.usersCollection = new OF.UsersCollection;
OF.usersCollection = new OF.UsersCollection;
OF.UsersCollection.fetch({ data: { "admin": OF.login.attributes.admin, "session":     OF.login.attributes.session } });
}

so you have a loop.

to Fix this remove form model new collection initialize and fetch.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top