简体   繁体   中英

Backbone: how to load a Collection in the view (inc require)

I am trying to load data from an API into a view. However the data doesn't turn up in my view.

I tried getting the collection information in de router, as well as in the model. However the date won't even console.log the data. Let alone that I can load the data into the view.

I am using require to load the JavaScript files. Can you have a look and see what I am doing wrong here?

I do see this console.log: console.log("People Collection is initialized");

And I can also see the page loaded and the json. But not the console.log of the data in the url function... In fact I get this error in the console:

Error: A "url" property or function must be specified

In the Backbone Router:

var OF = OF || {};

OF.AdminRouter = Backbone.Router.extend({

    routes: {
        "users": "goToUsers",
        "users/*other": "goToUsers"
    },

    goToUsers: function() {

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

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

        });

    }

});

The Collection:

var OF = OF || {};

OF.UsersCollection = Backbone.Collection.extend({

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

    url: function() {

        var that = this;

        var sendObj = {
            "admin": OF.login.attributes.admin,
            "session": OF.login.attributes.session
        };


        $.ajax({
            url: 'php/api/users/',
            type: "POST",
            dataType: "json",
            data: sendObj,
            success: function(data) {
                console.log(data);
            },
            error: function(data) {
                console.log("ERR: " + data);
            }

        });

    },

    model: OF.UsersMdl

});

The Model:

var OF = OF || {};

OF.UsersMdl = Backbone.Model.extend({

    default: {

        username: '',
        homefoldersize: '',
        email: ''

    },

    initialize: function(){

        //on change functions can be done here
        OF.usersCollection = new OF.UsersCollection();
        OF.usersCollection.fetch();

    },

    result: {
        success: false,
        message: ''
    },

    validate: function(att) {

    }

});

The View:

var OF = OF || {};

OF.UsersView = Backbone.View.extend({

    el: '#content',

    remove: function() {

        this.$el.empty();
        this.stopListening();
        return this;
    },

    initialize: function() {

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

    },

    render: function() {

        /*
        //first check if you are allowed to see this page
        if (!OF.login || !OF.login.isValid()) {
            OF.router.navigate('login', {trigger: true});
            return;
        }
        */

        //save this in that
        var that = this;

        //when importing of login page (and fill it with info) is done
        $.when(OF.template.get('users-usersField', function(data) {

            var htmlSource = $(data).html();
            var template = Handlebars.compile(htmlSource);
            var compiled = template(OF.usersMdl.attributes);

            //now place the page
            that.$el.html(compiled);

            //then start the menu
        })).then(function(){
                setTimeout(function(){
                    OF.menuView = new OF.MenuView;
                    OF.menuView.render();
                }, 100);

            });

        $('#logout').show();

    }

});

Thanks.

It seems to call the initialize of the collection twice and then continues to call the json function.

In your model's initialization you have

OF.usersCollection = new OF.UsersCollection();
OF.usersCollection.fetch();

But when you fetch your collection, it's going to initialize models for every result it gets back ... which will then trigger fresh collection fetches.

You don't need to create collections for your models inside your models, especially if the model is being created by the collection. Whenever you add a model to a collection (including when the collection creates the model after a fetch) the collection will associate itself with the model.

The general order of things should be:

  1. You define a url function on your collection which returns the URL where you can get the (raw JSON) models of that collection.
  2. You instantiate that collection, and then call fetch on the instance
  3. The collection makes an AJAX call (which you can affect by overriding fetch or sync ) and gets back the raw JSON for all of the models.
  4. The collection instantiates new models for each result it gets back; those models are automatically added to the collection, and their .collection is automatically set to the collection.
  5. Once OF.usersCollection.fetch().done(function() {... you can have your views start doing things, as your collection should now be all set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM