Search code examples
javascriptbackbone.js

cannot print the model data on console


    define(function(require) {
        var $ = require('jquery'),
                Backbone = require('backbone'),
                People = Backbone.Model.extend({
            initialize: function() {

                var people_object = new People({name: "How Bizarre", artist: "OMC"});
                var people_collections = new PeopleCollection([people_object]);
                console.log(people_collections.models);
            }

        }),
        PeopleCollection = Backbone.Collection.extend({
            model: People,
        });

        return {
            People: People,

        };

    });



  require(['jquery', 'backbone', 'app/models/persons'], function($,Backbone,persons{           
           var p = new persons.People();
   });

Here i write above code to display some data on console but when i try that i ve got following error message on the console.I am new to backbone js.can u tell me where am i wrong

<error>
w.pick
a.Model
r
Backbone.Model.extend.initialize
a.Model
r
Backbone.Model.extend.initialize
a.Model
r
Backbone.Model.extend.initialize
a.Model

Solution

  • First of all your error occurs from circular dependency (infinite loop), cause you have kind of infinite recursion. Any time you initialize people like new People(), initialize method of that model call the same 'new Person()' and so on....

    I guess you are using require.js.

    So try like this:

    human.js

    define(function(require){
        var Backbone = require('backbone');
    
        var Human = Backbone.Model.extend({
           defaults: {
              name: 'Test', 
              surname: 'Testovyan', 
              sex: 1
           }
        });
    
        return Human;
    
    });
    

    people.js

    define(function(require){
        var Backbone = require('backbone');
        var Human = require('path/to/human');
        var People = Backbone.Collection.extend({
            initialize: function () {
               console.log(this);
            },
            model: Human,
            url: '/path/to/remote/url'
        });
    
        return People;
    });
    

    controller_or_view.js

    define(function(require){
    
        require(['jquery', 'backbone', 'path/to/people'], function () {
            var newPeople = [{name: 'John', surname: 'Smith'}, {name: 'Jane', surname: 'Smith'}];   
            var people = new People(newPeople);
            });  
    
    });
    

    Here is working fiddle with the same code.

    This is the best way to create your collection of People. Create model, create collection with model attribute which references your model. Then Initialize your collection with array of objects, which then will automatically became models or initialize your collection without models and fetch them from remote.

    Hope this helps.