Backbone.js series six: Constructing Backbone objects

Source: Internet
Author: User
Tags add object constructor contains extend functions inheritance domain

Backbone constructors

I say backbone is simple because backbone only four constructors can be typically instantiated (basically, they are first inherited or subcategory). These four constructors include:

    • Backbone.model = function (attributes, {options}) {};
    • Backbone.collection = function ([models], {options}) {};
    • Backbone.router = function ({options}) {}; Can only be materialized once
    • Backbone.view = function ({options}) {};

Now let's take a look at what the default instance and stereotype properties are in each instance created by these constructors, and simply implement it with the new keyword without passing parameters. With the browser console open, you can see the instance and prototype properties more clearly.

Model

 
  
  
  1. var MyModel = new Backbone.model ();
  2. Console.log (' MyModel = new Backbone.model (); ');
  3. Console.log (' MyModel Instance Properties: ');
  4. Console.log (_.keys (MyModel));
  5. Console.log (' MyModel Prototype Properties & Methods: ');
  6. Console.log (_.keys (object.getprototypeof (MyModel)));

Collection

 
  
   
  1. var mycollection = new Backbone.collection ();
  2. Console.log (' var mycollection = new Backbone.collection (); ');
  3. Console.log (' mycollection Instance Properties: ');
  4. Console.log (_.keys (mycollection));
  5. Console.log (' mycollection prototype Properties & Methods: ');
  6. Console.log (_.keys (object.getprototypeof (mycollection)));

Router

 
  
    
  1. var myrouter = new Backbone.router ({routes:{' foo ': ' Bar '},bar:function () {}});
  2. Console.log (' var myrouter = new Backbone.router (); ');
  3. Console.log (' Myrouter Instance Properties: ');
  4. Console.log (_.keys (myrouter));
  5. Console.log (' Myrouter prototype Properties & Methods: ');
  6. Console.log (_.keys (object.getprototypeof (Myrouter)));

View

 
  
     
  1. var myview = new Backbone.view ();
  2. Console.log (' var myview = new Backbone.view (); ');
  3. Console.log (' MyView Instance Properties: ');
  4. Console.log (_.keys (MyView));
  5. Console.log (' MyView inherited Properties & Methods: ');
  6. Console.log (_.keys (object.getprototypeof (MyView)));

The properties of each constructor are readily available by backbone. However, you usually need to inherit (Backbone.Model.extend ()) your own domain-specific instances, prototype properties, and methods before you construct these functions.

Before continuing with the following sections, let's take a quick look at the optional parameter entries for each constructor. There is a section in this chapter that specifically describes the parameters, but you can now get a general idea of the optional argument items.

 
     
  1. var MyModel = new Backbone.model (attributes, {options});
  2. /*
  3. attributes = {data:value, data:value} [Value,value]
  4. Options = {
  5. Collection: {},
  6. URL: ',
  7. UrlRoot: ',
  8. Parse:boolean
  9. }
  10. */
  11. var mycollection = new Backbone.collection (model (s), {options});
  12. /*
  13. Models = model [Model,model,model] {model:data} [{model:data},{model:data}];
  14. Options = {
  15. URL: ',
  16. Model: {},
  17. Comparator:function () {} '
  18. }
  19. */
  20. var myview = new Backbone.view ({options});
  21. /*
  22. Options = {
  23. Model: {},
  24. Events: {} or function () {return {}}}
  25. Collection: {},
  26. El: ' or function () {return '},
  27. ID: ',
  28. ClassName: ' or function () {return '},
  29. TagName: ' or function () {return '},
  30. Attributes: {Attribute:value,attribute:value}
  31. }
  32. */
  33. var myrouter = new Backbone.router ({options});
  34. /*
  35. Options = {
  36. routes:{}
  37. }
  38. */
  39. /* Also pay attention to the historical option * *
  40. Backbone.History.start ({options});
  41. /*
  42. Options = {
  43. Pushstate:boolean,
  44. Root: ",
  45. Hashchange:boolean,
  46. Silent:boolean
  47. }
  48. */

Tips:

    1. The Router () constructor can be materialized more than once, but when it is given a SPA , it is usually only presented once.
    2. The backbone.history () constructor is constructed internally by the backbone library itself, when the library is parsed.
    3. Note that, as mentioned earlier, the prototypes for each constructor in all instances contain backbone.events.

Create subclasses Model (), Collection (), Router () , and View () constructors with internal backbone extend () helper functions

Building a model, collection, video, or router in backbone mode often involves having a default backbone constructor inherit (create a subclass or constructor) of your own domain-related properties and methods. This step utilizes the extend () auxiliary function, which is the constructor of an attribute. Do not confuse this function with the extend () in underscore.js .

In general, the extend () in backbone can accomplish the following functions:

    • Copy constructor inherited instance value
    • Let the new child constructor inherit the developer-defined stereotype properties and static properties
    • Facilitates a prototype inheritance between a new constructor (a child constructor) and an inherited constructor
    • Add Extend () helper functions to new child constructors, and new child constructors can be inherited to create chain chains of subclasses
    • Creates a initialize () callback function that can be invoked when the quilt constructor creates an instance and sets the context of the initialization function

For more information on how the backbone extend () method works, please read the following code, detailing the use of the extend () function to inherit a fictitious View constructor (with Backbone.view similar, but not dissimilar, logic. This code is not exactly the preparation code contained in the backbone.js , but rather an independent demonstration, from the code layer when Backbone.model, Backbone.collection, Backbone.view and backbone.router Quilt Classification (I am more accustomed to being called an extended child constructor) what happens when.

 
     
  1. /* Create a view constructor that is somewhat similar to the Backbone.view in Backbone.js * *
  2. var View = function (parameter1,parameter2) {
  3. This. IAm = ' View constructor ';
  4. /* Invokes the first initialization function in the prototype chain and sets its scope to this*/
  5. This.initialize.apply (this, arguments); Passing an array of arguments to the initialization function
  6. };
  7. /* When no initialization function is passed to the Extend () function, an empty initialization function is invoked to inherit the prototype of the view constructor.
  8. View.prototype.initialize = function () {};
  9. /* Create a generic static extend () function to create a subclass (subclass constructor) that is considered a property view constructor.
  10. View.extend = function (Protoprops, staticprops) {
  11. var parent = this;/* In code is a view constructor, that is, function inheritance is a static property.
  12. var child; The/*this will become a subclass constructor, specifically shown in code as subview*/
  13. if (Protoprops && _.has (Protoprops, ' constructor ')) {/* check if there is a replaceable constructor passed to extend ().
  14. Child = Protoprops.constructor; /* If there is, then use it as a child constructor.
  15. } else {
  16. /* If not, create a function (that is, a child constructor) that can be passed to the argument of the view () constructor's constructor.
  17. and set the text to the child constructor. This step duplicates the properties of the view constructor.
  18. Child = function () {
  19. Return parent.apply (this, arguments);
  20. };
  21. }
  22. /* Add static parent class properties and any static properties for extend (), of course the parent class contains extend () itself,
  23. therefore Subview () can now invoke extend () and sub constructs and can be used to continue/
  24. _.extend (Child, parent, staticprops);
  25. /* Let the prototype chain inherit the parent class (view in code), but do not call the parent class constructor
  26. Basically, Thsi connects the parent class constructor (view in code) to the prototype chain between the child constructors.
  27. var surrogate = function () {
  28. This.constructor = child;
  29. };
  30. Surrogate.prototype = Parent.prototype;
  31. Child.prototype = new Surrogate ();
  32. /* Use if to add a prototype property to the child constructor, all instances of the child constructors will inherit these properties.
  33. if (protoprops) {_.extend (Child.prototype, protoprops);}
  34. /* The static property of the view.prototype*/constructor, pointing to the parent class prototype (
  35. child.__super__ = Parent.prototype;
  36. Return child;/* Returns the child constructor, all ready to be called to inherit the parent class.
  37. };
  38. /* Inherit view, create a child constructor based on the view constructor (that is, inherit the view constructor, make subview inherit view).
  39. var Subview = View.extend ({
  40. Protopropshere: ' Protoprops ',
  41. Iam: ' Subview constructor ',
  42. Initialize:function (Parameter1,parameter2) {//When Subview creates an instance, runs the initialization
  43. Console.log (' Sub-constructor has been used, instance created ');
  44. Console.log (' the ' + parameter1 + ' + parameter2 + ' have been passed ');
  45. Console.log (' The value of this: ' + this. Iam + ', was correctly set ');
  46. }
  47. }, {
  48. Staticepropertieshere: ' Staticproperties '
  49. }
  50. );
  51. /* Verify static properties of Subview * *
  52. Console.log (Subview.staticepropertieshere);
  53. /* Create Subview instance, named MyView, to run initialization function pass option * *
  54. var myview = new Subview (' param1 ', ' param2 ');
  55. /* Verify the prototype properties of MyView * *
  56. Console.log (Myview.protopropshere);

Understanding the concept of extend () and its role makes it possible to understand the principles of backbone applications. I suggest you test this section over and over again until you fully understand the function and role of extend () . If you want to skip this section quickly, I'll summarize this section as follows:

    • extend () can create or inherit new application-specific object properties so that inherited objects are instantiated and then have these new instance features and methods.

When the extended constructor is instantiated, run the initialization code

When using extend () to extend Backbone.model, backbone.collection, Backbone.view , and backbone.router an initialization function, You can set up an instance that is created at any time by an inherited constructor. Basically, the initialization function is a callback function that is invoked at any time when an instance is initialized. In the following code, I provide an initialization callback function for an inherited Backbone.model Constructor, and then create an instance that runs the initialization function sequentially (in backbone.collection, Backbone.view same as in Backbone.router ).

 
  
      
  1. var MyModel = Backbone.Model.extend ({
  2. To the instance object being created.*/
  3. Log the properties in This/instance
  4. Initialize:function () {
  5. Console.log (_.keys (this));
  6. Console.log (_.keys (This.constructor.prototype)); where ' ll find name
  7. },
  8. Name: ' MyModel '
  9. });
  10. Creates an instance that verifies that initialization is invoked
  11. New MyModel;

Note that all parameters passed to the inherited constructor are also passed to the initialization callback function.

 
  
       
  1. var MyModel = Backbone.Model.extend ({
  2. Initialize:function (A,b,number) {Console.log (A,b,number)},//log paramaters
  3. });
  4. New MyModel ({A: ' A '},{b: ' B '},1); Passing properties, optional and random parameters

Tips:

    1. The text of the initialization function (this) is set to the instance that is created.
    2. When inheriting a backbone constructor, you should be aware of what parameters and what values the constructor needs when initializing an instance. For example, the first parameter that theBackbone.model constructor wants is the object (that is, the attribute) that contains the data in the model. The second parameter is the object that contains the initialization options. You can add additional parameters and simply pass to the initialization function.

Overloading inherited constructors

When using extend () , you pass a property called ' constructor ' as a value to a function, and the function is replaced with the property of the extend () . In the following code, I inherited not the Model constructor, but the constructor I passed.

 
  
        
  1. var SubModel = Backbone.Model.extend ({
  2. Constructor:function () {//extend This constructor, not Model
  3. This.foo = ' bar ';
  4. }
  5. });
  6.  
  7. mymodel = new Submodel ();
  8.  
  9. console.log (Mymodel.foo);//log Bar
  10.  
  11. /*cid an instance property set by the model constructor, but the log is not defined
  12. console.log (mymodel.cid);
  13.  
  14. The
  15. /*cid property is an instance property set by model () and we do not use model
  16. We are using a custom constructor, so MyModel has no CID attribute */

In the following code,MyModel still inherits the Model () prototype property, rather than the instance attribute (CID). If you overload this constructor and want to preserve the instance properties of the constructor, you can call extend ()and you need to run the backbone.[in the custom constructor Constructor].apply (this, arguments).

 
  
         
  1. var submodel = Backbone.Model.extend ({
  2. Constructor:function () {//Inherit this constructor, not model
  3. This.goo = ' Boo ';
  4. Backbone.Model.apply (this, arguments); Add Model Instance Property
  5. }
  6. });
  7. MyModel = new Submodel ();
  8. Console.log (Mymodel.goo); Log Boo
  9. Console.log (MYMODEL.CID); Log C1, CID is a model instance property


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.