A simple understanding of the Backbone.js model and the view of the source code _ Basic Knowledge

Source: Internet
Author: User
Tags bind constructor prev tagname

Backbone.model

Today we'll talk about the M in Backbone.js MVC, model is the core of backbone, contains the data of the content of the page display, as well as the various transformations, checksums, computations, rights control, service-side interaction around the data operation, you can Backbone.Model.extend () Generate your model, of course, the resulting model can also be used as a base class to expand more model

 var people = Backbone.Model.extend ({
     
 });

 var man = People.extend ({

 });

Backbone.model Api

Backbone.model provides a number of ways to implement a Model of the basic operations, of course, the most basic or backbone.events based on the event mechanism, in the Model attributes changes, the corresponding change: The attr event is triggered, and the following is the API provided:

There are ways to perform server-side operations on data:

    • Sync: The base class that wraps the BACKBONE.SYNC,XHR
    • Fetch: Used to get data from the server
    • Save: Persisting data to the service end
    • Destroy: Deleting data from the service side

The method of data operation in model:

    • Get: Getting data from attributes
    • Set: Setting Data to Attributes
    • Escape: Encode the data using the underscore _.escape
    • There is no corresponding data in the Has:attributes
    • unset: Deleting data from attributes
    • Clear: Empty attributes Data
    • Changed: A value that changes compared to the last state (performed over Set,unset)
    • Tojson: Serialization of attributes into an object
    • Parse: When the set item parse is true, initialization of the/set/unset/fetch and other data operations will be a resolution of the target data to return the resolved object, this method is an empty method, you need to override the override
    • Haschanged: Whether it has changed compared with the previous state (performed Set,unset)
    • Changeattributes: All values that occur compared to the previous state (performed by Set,unset)
    • Previous: Previous state (performed over Set,unset), corresponding value of this property
    • Previousattributes: All values in the previous state of a changed object with the last state (performed over Set,unset)

Model of the data validation method:

    • Validate: Used to validate data in model, override default method required
    • ValidationError: Returns the value returned when the most recent invalid
    • IsValid: Calling the _validate method

Here are some key APIs to explain:

Constructors

  var Model = Backbone.model = function (attributes, options) {
     var attrs = Attributes | | {};
     Options | | (options = {});
     This.cid = _.uniqueid (' C ');
     This.attributes = {};
     if (options.collection) this.collection = options.collection;
     if (options.parse) attrs = This.parse (attrs, options) | | {};
     Attrs = _.defaults ({}, Attrs, _.result (this, ' defaults '));
     This.set (attrs, options);
     this.changed = {};
     This.initialize.apply (this, arguments);
   

The constructor primarily sets the initialized data and options, and then generates a unique CID to mark model, and if the parse in the options is true, the initialization value is parsed by the parse method, and the set method is invoked. All the initial values are stored in attributes, and the Initialize initialization method is invoked. The initialization of model is complete.

Set

Model.set (attributes, [options])

The Set method sets the value into attribute, and when set Slient to true, it triggers the corresponding Change:attr event, and finally the change event is uniformly triggered, and the set method part of the code is as follows:

  Set:function (Key, Val, options) {//...)//key value can be a key value pair, or it can be a string that will be assigned to the Attrs property if (typeof key = = =
     ' object ') {attrs = key;
    options = val;
    else {(attrs = {}) [key] = Val;
    //////Check the Set value if (!this._validate (attrs, options) return false; unset = Options.unset; Unset is true to delete the value of the setting, Unset method is implemented via set (Key,val,{unset:true})//When the object is being set, the previousattributes is not assigned if (!c
     Hanging) {this._previousattributes = _.clone (this.attributes);
    this.changed = {};
 
    Current = this.attributes, prev = this._previousattributes;
 

    If the ID is set, the id attribute of the object is also changed if (This.idattribute in attrs) this.id = Attrs[this.idattribute];
     Set or delete action for (attr in attrs) {val = attrs[attr];
     if (!_.isequal (Current[attr], Val)) Changes.push (attr); if (!_.isequal (Prev[attr], Val)) {this.changed[attr] = val;//setting for model changed} else {delete This.cha
  NGED[ATTR];   } unset?
    Delete current[attr]: current[attr] = val;//If unset is set to True, delete operation}//silent event sent if change:attr is not false
     if (!silent) {if (changes.length) this._pending = options;  for (var i = 0, L = changes.length i < l i++) {This.trigger (' change: ' + changes[i], this, current[changes[i]],
     Options);
    }//Trigger Change event if (changing) return this;
      if (!silent) {while (this._pending) {options = this._pending;
      This._pending = false;
     This.trigger (' Change ', this, options);
    } this._pending = false;
    This._changing = false;
   
  return this;

 }

The whole process of set is to process the incoming value into a key-value pair, then verify the value, check the correctness, then start the setup operation, when the value of the check is changed, if there is, join a Changeed object, and then check the value of the unset, Make the appropriate add update delete operation. The change:attr and change events are then triggered sequentially.

Save

Model.save ([Attributes], [options])

The Save method is used to persist data to the client, using Create,update or patch depending on the different data and configuration, and triggering the sync event, which is part of the code:

  Save:function (Key, Val, options) {//...//. When the Wait property is set to True, the Save method does not execute the Set method (not triggering the Change event), only the V
    Alidate if (attrs &&!options.wait) {if (!this.set (attrs, Options)) return false;
    else {if (!this._validate (attrs, Options)) return false; //If Wait is true, set this.attributes if (attrs && options.wait) {this.attributes = _.extend ({}, attrib
    Utes, attrs);
    //... var model = this;
    var success = options.success;
     options.success = function (resp) {//Ensure attributes are restored, during synchronous.
     model.attributes = attributes;
     var serverattrs = Model.parse (resp, options); If wait is true, the set operation is made after the request returns if (options.wait) serverattrs = _.extend (Attrs | |
     {}, Serverattrs);
     if (_.isobject (serverattrs) &&!model.set (serverattrs, Options)) {return false;
     if (success) success (model, RESP, options); Triggering Sync Event MoDEl.trigger (' sync ', model, RESP, options);

    };
    Generate XHR OnError callback function Wraperror (this, options); Select method methods = This.isnew ()? ' Create ': (Options.patch?)
    ' Patch ': ' Update ');
    if (method = = = = ' Patch ') options.attrs = attrs;
 
    XHR = This.sync (method, this, options);
    Restore attributes.
    if (attrs && options.wait) this.attributes = attributes;
  Returns the XHR object return XHR;

 }


The most notable thing in save is the wait setting, and when the wait is true, the save return will perform a set operation after XHR returns, rather than a set operation before XHR, so the change event triggers a different timing.

Previously said that the entire backbone are connected through the event, so it is very important to know and grasp the timing of the event, otherwise it will lead to some strange problems in the development process.

Backbone.view
we have already analyzed the event, Model, and collection code in backbone, and now we look at the v part of MVC, That is, backbone.view,view in the backbone is mainly used to communicate the DOM and backbone.model/collection in the page, the logical operation of the page, the binding of DOM events, and so on, the View part of the code is very simple answer, Plus comments are only about 110. The view section has an API:

There are few methods, and the following are some of the APIs:

Construction method

  var viewoptions = [' Model ', ' collection ', ' El ', ' id ', ' attributes ', ' className ', ' tagName ', ' events '];
 var View = Backbone.view = function (options) {
   this.cid = _.uniqueid (' View ');
   Options | | (options = {});
   _.extend (This, _.pick (options, viewoptions));
   This._ensureelement ();
   This.initialize.apply (this, arguments);
   This.delegateevents ();
 };

The construction method generates a unique CID for view, starts with ' view ', then merges the target attribute viewoptions, calls _ensureelement to Judge El, and then calls Delegateevents for method binding. Initialization completed.

Delegateevents

View.setelement (Element)

   setelement:function (element, delegate) {
    if (this. $el) this.undelegateevents ();// If this. $el is already present, an event

    $el//is assigned to the Lo-dash, essentially a jquery or Zepto object this
    . $el = Element instanceof backbone.$? element:backbone.$ (element);
    Assigning DOM element to El
    This.el = this. $el [0];

     If no value is explicitly passed, the event binding if
    (Delegate!== false) this.delegateevents ();
    return this;
   }

The Setelement method is used to set the view's corresponding element, which is invoked at new time, and can be called to reset the DOM element of the view if it is intended to be directed during use.

_ensureelement

  _ensureelement:function () {
     //If El is already set up, call Setelement method if
    (!this.el) {//If no setting, generate an Element object, Then call the Setelement method
     var attrs = _.extend ({}, _.result (this, ' attributes '));
     if (this.id) attrs.id = _.result (this, ' id ');
     if (this.classname) attrs[' class ' = _.result (this, ' className ');
     var $el = backbone.$ (' < ' + _.result (this, ' tagName ') + ' > '). attr (attrs);
     This.setelement ($el, false);
    else {
     this.setelement (_.result (This, ' El '), false);
    }
  

_ensureelement This method is an internal method, used in the constructor, to judge that the specified El does not exist on the page, and if so, to assign a value to $el, and if not, generate a $el, but note that the object is not landed in the DOM tree.

Delegateevents

Delegateevents ([events])//*{"event selector": "Callback"}*////{//' MouseDown. Title ': ' Edit ',
   ' Click button ': ' Save ',//' click. Open ': function (e) {...} } delegateevents:function (events) {//If events are not present, return directly if (!) (! Events | | (Events = _.result (this, ' events '))]
   
      return this;
   
      Unbind All Events first this.undelegateevents ();
       Process each event for (Var key in events) {var method = Events[key];
       Parse callback function if (!_.isfunction (method)) methods = This[events[key]];
   
       if (!method) continue;
       Analysis of the selector var match = Key.match (delegateeventsplitter);
       var eventName = match[1], selector = match[2];
   
       Method = _.bind (method, this); The bound event names are made up of EventName + '. Delegateevents ' + CID,//This allows you to select all events in this view at undelegateevents eventName = '
       . delegateevents ' + this.cid;
    if (selector = = ") {this. $el. On (EventName, method);   } else {this. $el. On (EventName, selector, method);
   } return this;

 }

In view you can use a key:value set to specify the corresponding event, and the constructor will invoke delegateevents to bind at initialization time, noting that all the elements specified in the key must be $el, which means that the element must be $ The child node of El, or the binding fails.

The difference between view and other backbone modules is that there is no built-in custom event of its own, and of course he also combines the events module, but all the incidents need to be built on their own. View is mainly an MVC model of the load, in fact, the real function is not much, in fact, from the model level V in the front-end development is closest to the business logic, so most of the logic in view is the developer to expand their own.

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.