A Brief Introduction to the Model and View source code of Backbone. js, backbone. jsmodel

Source: Internet
Author: User

A Brief Introduction to the Model and View source code of Backbone. js, backbone. jsmodel

Backbone. Model

Today, let's talk about Backbone. M and Model in js MVC are the core part of backbone, including the data displayed on the page, as well as various conversions, verification, computing, and permission control around data operations, server interaction and other operations, you can use Backbone. model. extend () generates your model. Of course, the generated model can also be used as a base class to expand more models.

 var People = Backbone.Model.extend({      }); var Man = People.extend({ });

Backbone. Model Api

Backbone. model provides a large number of methods for implementing basic operations on a Model. Of course, the most basic method is based on Backbone. events event mechanism, when the attributes of the Model changes, the corresponding change: attr event will be triggered. The following is the provided API:

The following describes how to perform server-side operations on data:

  • Sync: encapsulates the basic classes of Backbone. sync and xhr.
  • Fetch: used to obtain data from the server.
  • Save: persists data to the server.
  • Destroy: delete data from the server

Data Operation Method in model:

  • Get: get data from attributes
  • Set: set Data to attributes
  • Escape: encode the data using underscore _. escape
  • Has: attributes contains no corresponding data
  • Unset: delete data from attributes
  • Clear: clear attributes data
  • Changed: compared with the previous state (set, unset executed ),
  • ToJSON: serialize attributes into an object
  • Parse: when the set item parse is true, a parsed object will be returned for the target data during initialization/set/unset/fetch and other data operations. This method is empty, overwrite
  • HasChanged: whether or not it has changed compared with the previous state (set and unset executed)
  • ChangeAttributes: All values compared with the previous state (set, unset executed)
  • Previous: The value corresponding to this attribute in the previous state (set, unset executed)
  • Previusattributes: all values of the previous state of the object that have changed with the previous state (set and unset executed)

Data Verification Method in model:

  • Validate: used to verify the data in the model. The default method must be overwritten.
  • ValidationError: return the value of the last invalid.
  • IsValid: Call the _ validate Method

The following describes some key APIs:

Constructor

  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 mainly sets the initialized data and options, and then generates a unique cid to mark the model. If parse in options is true, the initialization value is parsed using the parse method and the set method is called. All initial values are stored in attributes and the initialize initialization method is called. Model Initialization is complete.

Set

model.set(attributes, [options])

The set method will set the value to the attribute. If the slient is set to true, the corresponding change: attr event will be triggered, and the change event will be triggered in a unified manner, the code for the set method is as follows:

 

Set: function (key, val, options ){//...... // The key value can be either a key-value pair or a string. Pass the value assignment to if (typeof key = 'object') {attrs = key; options = val;} else {(attrs = {}) [key] = val ;}//.... // verify the set value if (! This. _ validate (attrs, options) return false; unset = options. unset; // when unset is set to true, the set value is deleted. The unset method uses set (key, val, {unset: true }) implemented // when the object is being set, do not assign the value of if (! Changing) {this. _ previusattributes = _. clone (this. attributes); this. changed = {};} current = this. attributes, prev = this. _ previusattributes; // if Id is set, the id attribute of the object is also changed if (this. idattris in attrs) this. id = attrs [this. idattris]; // set or delete the operation for (attr in attrs) {val = attrs [attr]; if (! _. IsEqual (current [attr], val) changes. push (attr); if (! _. IsEqual (prev [attr], val) {this. changed [attr] = val; // set for changed of model} else {delete this. changed [attr];} unset? Delete current [attr]: current [attr] = val; // If unset is set to true, delete it.} // when silent is not false, send 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 the 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 entire set process is to process the passed value, convert it into a key-value pair, verify the value, check the correctness, and then start setting, the value is changed when it is set. If yes, it is added to a changeed object. Then, check the unset value and add, update, and delete the value accordingly. The change: attr and change events are triggered in turn.

Save

model.save([attributes], [options])

The save method is used to persist data to the client. The create, update, or patch method is used based on different data and configuration, and the sync event is triggered. The following code is used:

Save: function (key, val, options ){//...... // when the wait attribute is set to true, the save method first does not execute the set Method (does not trigger the change event), and only executes the validate 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 ({}, attributes, attrs );}//..... var model = this; var success = options. success; options. success = function (resp) {// Ensure attributes are restored during synchronous saves. model. attributes = attributes; var serverAttrs = model. parse (resp, options); // If wait is True, then the set operation if (options. wait) serverAttrs = _. extend (attrs | |{}, serverAttrs); if (_. isObject (serverAttrs )&&! Model. set (serverAttrs, options) {return false;} if (success) success (model, resp, options); // trigger the sync event model. trigger ('sync', model, resp, options) ;}; // generate the XHR onerror callback function wrapError (this, options); // select method = 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; // return the xhr object return xhr ;}


The most important thing to pay attention to in save is the wait settings. When wait is true, the result of save will be executed after xhr returns, rather than before xhr, therefore, the timing of the change event is different.

As we have said before, the entire Backbone is connected through events. Therefore, it is very important to understand and grasp the event triggering time. Otherwise, some strange problems may occur during the development process.

Backbone. View
We have analyzed the Event, Model, and Collection code in backbone. Now let's take a look at section V in MVC, that is, Backbone. view is mainly used in Backbone to communicate with DOM and Backbone in the page. model/Collection, page logical operations, DOM Event binding, etc. The View part of the code is very simple, and the comments are only about 110. The View part has the following APIs:

There are not many methods. I will introduce some APIs below:

Constructor

  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(); };

A unique cid is generated for the View in the constructor. It starts with 'view', merges the viewOptions of the Target attribute, and CALLS _ ensureElement to determine the el condition, call delegateEvents to bind the method. The Initialization is complete.

DelegateEvents

View. setElement (element) setElement: function (element, delegate) {if (this. $ el) this. undelegateEvents (); // if this already exists. $ el: unbind events // assign values to $ el. Essentially, this is a jquery or Lo-Dash and Zepto object. $ el = element instanceof Backbone. $? Element: Backbone. $ (element); // assign the dom element to el this. el = this. $ el [0]; // if no value is explicitly transferred, bind the event if (delegate! = False) this. delegateEvents (); return this ;}

The setElement method is used to set the element corresponding to the View. This method will be called when new is used. If you want to change the dom element orientation of the View during use, you can use this method to reset the settings.

_ EnsureElement

_ EnsureElement: function () {// if you have set el, call the setElement method if (! This. el) {// if not set, generate an element object and call the setElement method var attrs = _. extend ({},_. result (this, 'bubuckets'); 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: an internal method used in the constructor to determine whether the specified el exists on the page. If yes, assign a value to $ el. If no, A $ el is generated, but note that this object is not implemented in the dom tree.

DelegateEvents

DelegateEvents ([events]) // * {"event selector": "callback"} * // {// 'mousedown. title ': 'edit', // 'click. button ': 'save', // 'click. open ': function (e ){...} //} delegateEvents: function (events) {// if no events exists, 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 the callback function if (! _. IsFunction (method) method = this [events [key]; if (! Method) continue; // analyzes the selector var match = key. match (delegateEventSplitter); var eventName = match [1], selector = match [2]; method = _. bind (method, this); // All bound event names are based on eventName + '. delegateEvents '+ cid, // in this way, you can select all event eventName + =' for this View when undelegateEvents '. 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. during initialization, the constructor will call delegateEvents for binding, note that the parent element of all elements specified in the key must be $ el, that is, the element must be a child node of $ el. Otherwise, the binding fails.

One difference between View and other backbone modules is that they do not have their own built-in custom Events. Of course, they also combine the Events module, but all Events need to be created by themselves. View is mainly carried by an MVC model. In fact, there are not many real functions. In fact, at the model level, V is the closest to the business logic in front-end development, therefore, most of the logic in View is extended by developers themselves.

Articles you may be interested in:
  • Prepare study notes in simple View in the Backbone. js framework
  • Describes the MVC Structure Design Concept of the Backbone. js framework of JavaScript.
  • In-depth parsing of the event mechanism in JavaScript framework Backbone. js
  • Lightweight javascript framework Backbone User Guide
  • Some tips for using Backbone. js
  • Backbone. js 0.9.2 source code annotation Chinese translation version
  • Hello World program instance of Backbone. js
  • Details about the set in Backbone. js
  • Details about Javascript MVC Framework Backbone. js
  • Some suggestions for using JavaScript's Backbone. js framework

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.