Explains the MVC Structure Design Concept of the Backbone. js framework of JavaScript, and backbone. jsmvc

Source: Internet
Author: User

Explains the MVC Structure Design Concept of the Backbone. js framework of JavaScript, and backbone. jsmvc

What is Backbone. js?
Backbone. js is the first of the top ten JS frameworks. Backbone. js is a heavyweight js MVC application framework and also the originator of the js MVC framework. It uses the Models data model for key-value binding and custom Event processing, and uses the model collection tool Collections to provide a rich set of APIS for enumeration, view Views are used to process events and interact with existing applications through the JSON interface.

In short, Backbone is a js library that implements the web Front-end MVC mode.

What is MVC?
MVC: the backend server first (process 1) obtains the page address through the browser, parses the URL, obtains a URL for the View, and then parses it through the controller, then, find the corresponding data (process 2), find the data, and then return the data Model to the controller (process 3). Then, the controller processes the data, return to View (process 4), that is, update View. This structure is very clear and easy to implement at the backend.

MVC mechanism in Backbone
Backbone presents the data as a model. You can create a model, verify and destroy the model, and even save it to the server. When the model attribute changes due to changes in the UI, the model triggers the "change" event. All views that display model data receive notifications of this event, and the view is re-rendered. You do not need to search the DOM to search for the elements with the specified id to manually update the HTML. -When the model changes, the view automatically changes. --- Baidu encyclopedia

Mode: a common solution to the problem

-Design mode: factory mode, adapter mode, and observer Mode
-Framework mode: MVC, MVP, and MVVM
Controller: connects views and models through controllers.

The idea of MVC mode:

Is to separate the model from the view and connect them through the Controller.
The MVC mode on the server is very easy to implement.
Model: Model refers to data. Model is the core of all js applications, including interactive data and a large number of related logic: conversion, verification, calculation attributes, and access control. You can extend Backbone. Model in a specific way.

View: View that you can see on the page. Each single data model corresponds to a View

The web page itself is a large view, and it is not easy to perform separation operations. backbone. js is suitable for complicated large-scale development and solves these problems for us.

Backbone Module
Backbone has the following modules:

  • Events: event-driven module
  • Model: Data Model
  • Collection: model set
  • Router: Router (corresponding to hash value)
  • History: enables History Management.
  • Sync: Synchronous Server Mode
  • View: View (including event behavior and rendering page-related methods)

Collection is a unified control of individual data models.

Directly create an object
Backbone depends on Underscore. js, DOM processing depends on Backbone. view and jQuery. before js, Underscore. js must be introduced before it, while jQuery is also better to introduce it together, and then introduce Backbone. js

New is followed by a constructor, while Backbone is used as the namespace of the constructor.

Model Module

Backbone.Model.extend(properties, [classProperties])

Backbone extends the instance method and static method through extend:

<Script type = "text/javascript"> // The first parameter received by extend is a json string used to extend the instance method. // The second parameter is also a json string, used to extend the static method var M = Backbone. model. extend ({abc: function () {// instance method alert ("hello backbone") ;},{ def: function () {// static method alert ("hi") ;}}); var model = new M; model. abc (); // The instance method uses the instance object to access M. def (); // The static method is directly mounted to the constructor. You can directly access the constructor. </script>

Static methods actually have an extra namespace. The above are the instance and static methods added to the constructor.

 var M = Backbone.Model.extend({})

Extend is used to expand the constructor of the model. M is the constructor after expansion.

Inheritance

<Script type = "text/javascript"> // inherit var Mod = backbone. model. extend ({abc: function () {alert (123) ;}}); var ChildMod = Mod. extend (); var model = new ChildMod; model. abc (); // subclass inherits the method of the parent class </script>

Backbone source code structure

1: (function (){

2: Backbone. Events // custom event

3: Backbone. Model // Model constructor and prototype Extension

4: Backbone. Collection // set constructor and prototype Extension

5: Backbone. Router // Router configurator constructor and prototype Extension

6: Backbone. History // router constructor and prototype Extension

7: Backbone. View // View constructor and prototype Extension

8: Backbone. sync // asynchronous request tool Method

9: var extend = function (protoProps, classProps) {...} // self-Extended function

10: Backbone. Model. extend = Backbone. Collection. extend = Backbone. Router. extend = Backbone. View. extend = extend; // self-Scaling Method

11:}). call (this );
Js mvc Responsibility Division
M model

Business Model: business logic, process, status, rules
(CORE) Data Model: business data, data validation, addition, deletion, modification, and query (AJAX)
V View

(CORE) view: definition, management, and Configuration
Template: definition, configuration, and management
Components: definition, configuration, and management
(CORE) User event configuration and management
User input validation, configuration, and management
C Controller/Distributor

(CORE) event distribution, model distribution, and view Distribution
No data processing or business processing, that is, the business is irrelevant.
Extension: Permission control, exception handling, etc.
C is the core of the JSMVC framework. It implements centralized configuration and management and can have multiple controllers.
Tool Library

Mainly asynchronous requests and DOM operations, which can depend on jQuery and so on.

Model refers to data in one row, and Collection refers to managing multiple data items in the Model.

Model
We use Backbone. Model to represent all data in the application. Data in models can be created, verified, destroyed, and saved to the server.

Object Assignment Method
1. Define directly and set the default value

 Trigkit = Backbone.Model.extend({       initialize : function () {         alert('hi!');       },       defaults:{         age : '22',         profession : 'coder'       }     });    var coder = new Trigkit;    alert(coder.get('age'));//22

2. Definition during assignment

<script type="text/javascript">   Trigkit = Backbone.Model.extend({     initialize : function () {       alert('hi!');     }   });   var t = new Trigkit;   t.set({name :'huang',age : '10'});   alert(t.get('name'));</script> 


Methods In the object

<Script type = "text/javascript" src = "Underscore. js "> </script> <script type =" text/javascript "src =" backbone-1.1.2.js "> </script> <script type =" text/javascript "> var Trigkit4 = Backbone. model. extend ({initialize: function () {alert ("hello world! ") ;}, Defaults: {name: 'hangsan', age: 21}, aboutMe: function () {return 'My name '+ this. get ('name') + ', this year' + this. get ('age') + 'age' ;}}); var t = new Trigkit4; alert (t. aboutMe (); </script>

When the model is instantiated, its initialize method can accept any instance parameter. its working principle is that the backbone model itself is a constructor, so you can use new to generate an instance:

var User = Backbone.Model.extend({  initialize: function (name) {    this.set({name: name});  }});var user = new User('trigkit4');alert(user.get('name'), 'trigkit4');//trigkit4

Check the source code of backbone:

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) ;}; initialize: function () {}, // initialize is the default empty function

Model event binding
In order to update the view in time, we need to process and respond to user events through the event binding mechanism:

 

  <script type="text/javascript">    var Task = Backbone.Model.extend({      initialize: function () {        this.on("change:name", function (model) {          alert("my name is : " + model.get("name"));        });      }    });    var task = new Task({ name:"oldname", state:"working"});    task.set({name:"trigkit"});//    object.on(event, callback, [context])  </script>

About event binding, there are on, off, trigger, once, listenTo, stopListening, listenToOnce and other methods, specific reference: http://documentcloud.github.io/backbone/#Events

Collection
Backbone. Collection is an ordered set of Model objects. Because Model is a data record, that is, Collection is equivalent to a dataset. It has a series of tool methods, such as adding, deleting elements, obtaining length, sorting, and comparison. To put it bluntly, it is a set class for saving models.

<Script type = "text/javascript"> var Book = Backbone. model. extend ({defaults: {title: 'default'}, initialize: function () {alert ('Hello backbone! '); // 3 pops up}); BookShelf = Backbone. collection. extend ({model: Book}); var book1 = new Book ({title: 'book1'}); var book2 = new Book ({title: 'book2 '}); var book3 = new Book ({title: 'book3'}); // var bookShelf = new BookShelf ([book1, book2, book3]); // note that this is an array, or use add var bookShelf = new BookShelf; bookShelf. add (book1); bookShelf. add (book2); bookShelf. add (book3); bookShelf. remove (book3); // Based on the js library underscore, you can also use the each method to obtain the data bookShelf in the collection. each (function (book) {alert (book. get ('title') ;}); </script>

Collection. model overwrites this attribute to specify the model classes contained in the set. You can pass in the original property object (and array) to add, create, and reset. The imported property is automatically converted to the appropriate model type.

View
Backbone. View can bind dom elements and client events. Html in the page is rendered through the render method of views. When creating a view, you need to upload a model as the data.

View. $ el: cache jQuery object for a view element. A simple reference, rather than a re-wrapped DOM element.
A simple View:

<Head> <meta charset = "UTF-8"> <title> Document </title> <script type = "text/javascript" src = "jquery-1.9.1.min.js"> </script> <script type = "text/javascript" src = "Underscore. js "> </script> <script type =" text/javascript "src =" backbone-1.1.2.js "> </script> <script type =" text/javascript "> var TestView = Backbone. view. extend ({// create a view, which is actually an html dom node initialize: function () {this. render () ;}, render: function () {// Rendering Method this.cancel.html ('Hello World'); // this. el is an HTML node. The jQuery html method is used to fill in the content return this ;}); $ (function () {var test = new TestView ({el: $ ('# body')}); // create a view instance with the target node as the el parameter, the render function will be automatically called and the rendering result will be filled in el. // test. render (); // if you have not called render in initialize, you need to call it once here }); </script> 

All views of elview. el have a DOM element (el attribute), even if the element is not inserted into the page. A view can be rendered at any time, and then inserted into the DOM at a time. This reduces reflows and repaints as much as possible to achieve high-performance UI rendering. This. el can be created from the tagName, className, id, and attributes of the view. If neither of them is specified, el will be an empty div. -- Official Website

Extended method extend
Models, sets, views, and routers all have an extend method used to expand prototype attributes and static attributes and create custom models, sets, views, and vro classes.

Backbone.Model.extendBackbone.Model.extend(properties, [classProperties])

To create your own Model class, you can expand Backbone. Model and provide the instance properties (attributes), and optional classProperties (class attributes) that can be directly registered to the constructor ).

Backbone.View.extendBackbone.View.extend(properties, [classProperties])

Create a custom View class. We usually need to reload the render function, declare events, and specify the root element for the view through tagName, className, or id. Backbone. View is bound to the "change" event of the model through the render function of the View-model data is instantly displayed in the UI.

Backbone.Collection.extendBackbone.Collection.extend(properties, [classProperties])

Create a Collection class by extending Backbone. Collection. Instance property parameter properties and class property parameter classProperties are directly registered to the constructor of the set.

Backbone.Router.extendBackbone.Router.extend(properties, [classProperties])

Create a custom route class. When a URL segment is matched, the defined action is executed and the route action key-value pair can be defined through routes.

Router and controller
Controller is the name of Backbone 0.5 and is now called Router.

Backbone. Router provides many methods for client routing and can connect to specified actions and events ).
During page loading, when the application has created all the routes, you need to call Backbone. history. start ()

View the following example:

<script type="text/javascript">    var AppRouter = Backbone.Router.extend({      routes: {        "index" : "index",        "task/:id": "task",        "*acts": "tasklist"      },      index: function() {        alert("index");      },      tasklist: function(action) {        alert(action);      },      task: function(id) {        alert(id);      }    });    var app = new AppRouter;    Backbone.history.start();  </script>

After opening the page in the browser, add the following to the html of the url:

#/index#/task/1#/test/xxxx

Index, 1, test/xxxx

This is the Router function.

Articles you may be interested in:
  • A Brief Introduction to the Model and View source code of Backbone. js
  • Prepare study notes in simple View in the Backbone. js framework
  • 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.