Search code examples
javascriptbackbone.js

How to create collection through global variable in backbone.js?


I am sent the assistance by many advisors in stackoverflow, In part of my problem is solved but a few problems are remained.

I consult the answer and I has try to solve the problem as a result from it i understood the javascript namespacing pattren.

A namespacing pattern to avoid polluting the global namespace.
More details on this namespacing pattern
How do I declare a namespace in JavaScript?

I suffer from problem that global variable is created successfully however, i don't handle the generated variable.

collecton.js

    var app = app || {};
(function () {
    'use strict';
    var collections = app.Collection = app.Collection || {};

    collections.VideoLists =  Backbone.Collection.extend({
        model: app.Model,
        initialize: function(){
            console.log('load Collection');
        }
    });

    app.Collection = collections.VideoLists;
})();

model.js

var app = app || {};
(function() {
    'use strict';
    var models = app.Model = app.Model || {};

    models.Video = Backbone.Model.extend({
        initialize: function(){
            console.log('model create');
        },
        defaults:{
                 id : "1",
                 url : "/assets/videos/call/MOV01718.mp4",
                 imgSrc : "assets/img/call/1_thumbnail.png",
                 title: "call situation conservation"
        }
    });
  app.Model = new models.Video();
})();

router.js

listRoute: function(id) {
          //generate the collection using the listsection
          var videoList = this.collection;
          var getId = parseInt(id);
            switch (getId) {
              case 1:
                new videoList([
                    {
                      id : "1",
                      url : "/assets/videos/call/MOV01718.mp4",
                      imgSrc : "assets/img/call/1_thumbnail.png",
                      title: "call situation conservation"
                    },
                    {
                      id : "2",
                      url : "/assets/videos/call/MOV01722.mp4",
                      imgSrc : "assets/img/call/2_thumbnail.png",
                      title: "call situation conservation"
                    }
                  ]);
                break;

  //app.router init part
  initialize: function() {
            // create the layout once here
            this.layout = new views.Application({
                el: 'body',
            });
            // create model and collection once here
            this.model = app.Model;
            this.collection = app.Collection;
        }

Please see the below picture enter image description here

I think the generation has been done properly.
But I do not understand why I get this error.

I tried at first
1. Don't generate collection with new function (as current my source)
2. Create variable videoList as Object.
3. Stores Collection in a variable.
4. Use collection.create function.
For example, list.create({id:'dasdsad'});

However, this attempt eventually yielded the same result.
How can i solve them?


Solution

  • What's the purpose of the namespacing pattern?

    You are misusing the namespace pattern. The goal in this case is to namespace all your custom Backbone classes constructor into the app object.

    In order to keep everything clearly separated, put all your collections constructor into the app.Collection object, models constructor within app.Model, etc.

    If you inspect the app namespace after all the classes are created, it should look like the following:

    var app = {
        Collection: {
            VideoList: /* video list constructor */
        },
        Model: {
            Video: /* video model constructor */
        },
        View: {
            /* same thing goes for views */
        }
    };
    

    The app namespace shouldn't1 contain instances, mainly constructors.

    Do not overwrite the constructors references:

    app.Model = new models.Video();
    

    Create an instance when you need one only, and keep it in the scope it's needed.

    this.model = new app.Model.Video();
    this.collection = app.Collection.VideoList();
    

    Instances and constructors

    To really understand the previous point, you need to understand the differences between a constructor and an instance. The concept is applicable to other OOP languages, but I'll keep the description within the JavaScript language specifics.

    A constructor is just a function. From the MDN doc on Object.prototype.constructor:

    All objects will have a constructor property.

    [...]

    The following example creates a prototype, Tree, and an object of that type, theTree.

    function Tree(name) {
      this.name = name;
    }
    
    var theTree = new Tree('Redwood');
    

    As seen in the previous example, to create an instance, use the new operator. What is the 'new' keyword in JavaScript?

    The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

    new constructor[([arguments])]
    

    Creating custom constructors lets you define custom types (classes). There are multiple ways to create more complex custom types in JavaScript but that's another discussion. For more details, see How to “properly” create a custom object in JavaScript?

    Fortunately, Backbone provides an easy (opinionated) way to define new types, the extend function, which is available on all the Backbone's base types.

    var ModelConstructor = Backbone.Model.extend({ /*...*/ });
    
    var modelInstance = new ModelConstructor();
    

    Note that myVariable = MyConstructor will just pass a reference of the constructor to myVariable, it won't create a new instance. You could still use the variable as the constructor though.

    var myInstance = new myVariable();
    

    Ordering and dependencies

    If you look at your code, you'll notice that the app.Collection.VideoList class uses the app.Model.Video as the value for the model property.

    This means that app.Collection.VideoList depends on the availability of the app.Model.Video class. So the collection file should be inserted into the document after the model file.

    Like in the other answer of mine you linked:

    <script src="js/models/todo.js"></script><!-- no dependencies -->
    <script src="js/collections/todos.js"></script><!-- depends on the model -->
    <script src="js/views/todo-view.js"></script><!-- depends on the collection and the model -->
    <script src="js/views/app-view.js"></script><!-- depends on the todo-view -->
    <script src="js/routers/router.js"></script><!-- depends on the app view -->
    <script src="js/app.js"></script><!-- depends on the router -->
    

    1. The app namespace object could contain an instance of an object if you want to share it between all your app, like a singleton, or a namespaced global, or a service.