Detailed explanation of Javascript MVC Framework Backbone. js, mvcbackbone. js

Source: Internet
Author: User
Tags tojson

Detailed explanation of Javascript MVC Framework Backbone. js, mvcbackbone. js

As JavaScript programs become more and more complex and often require collaborative development by a team, code modularization and organization specifications become very important. The MVC mode is the classic mode of code organization.

(...... MVC introduction .)

(1) Model

Model indicates the data layer, that is, the data source required by the program, which is usually expressed in JSON format.

(2) View

View indicates the presentation layer, that is, the user interface. For a webpage, It is the HTML code of the webpage that the user sees.

(3) Controller

Controller indicates the control layer, which is used to process the raw data (Model) and transmit it to the View.

Because Web programming is different from client programming, based on MVC, the JavaScript community generates various variant frameworks, such as Model-View-Presenter and MVVM (Model-View-ViewModel, some people refer to the various models of this framework as MV *.

The Framework has the advantage of organizing code reasonably, facilitating team cooperation and future maintenance. The disadvantage is that there is a certain learning cost, and you can only adopt the method.

Loading of Backbone

Copy codeThe Code is as follows:
<Script src = "/javascripts/lib/jquery. js"> </script>
<Script src = "/javascripts/lib/underscore. js"> </script>
<Script src = "/javascripts/lib/backbone. js"> </script>
<Script src = "/javascripts/jst. js"> </script>
<Script src = "/javascripts/router. js"> </script>
<Script src = "/javascripts/init. js"> </script>

Backbone. View

Basic usage

The Backbone. View method is used to define the View class.
Copy codeThe Code is as follows:
Var AppView = Backbone. View. extend ({
Render: function (){
$ ('Main'). append ('}
});

The code above defines a View class AppView through the extend method of Backbone. View. This class contains a render method to place a view on a webpage.

When using this function, you must first create a View class instance and then call the render method through the instance to display the view on the webpage.
Copy codeThe Code is as follows:
Var appView = new AppView ();
AppView. render ();

The code above creates an AppView instance of the View class appView and then calls appView. render to display the specified content on the webpage.

When creating a view instance, you must specify a Model.
Copy codeThe Code is as follows:
Var document = new Document ({
Model: doc
});

Initialize Method

The view can also define the initialize method. When an instance is generated, this method is automatically called to initialize the instance.

Copy codeThe Code is as follows:
Var AppView = Backbone. View. extend ({
Initialize: function (){
This. render ();
},
Render: function (){
$ ('Main'). append ('}
});
Var appView = new AppView ();

After the above Code defines the initialize method, it eliminates the need to manually call appView. render () after the instance is generated.

El attribute, $ el attribute

In addition to specifying the webpage elements bound to the "View" in the render method, you can also use the el attribute of the view to specify the webpage elements.
Copy codeThe Code is as follows:
Var AppView = Backbone. View. extend ({
El: $ ('main '),
Render: function (){
This. $ el. append ('}
});

The above Code directly binds the webpage element with the render method, and the effect is exactly the same. In the code above, besides the el attribute or the $ el attribute, the former represents the specified DOM element, and the latter represents the jQuery object corresponding to the DOM element.

TagName and className attributes

If you do not specify the el attribute, you can also specify it using the tagName attribute and className attribute.

Copy codeThe Code is as follows:
Var Document = Backbone. View. extend ({
TagName: "li ",
ClassName: "document ",
Render: function (){
//...
}
});

Template Method

The template attribute of the view is used to specify a webpage template.
Copy codeThe Code is as follows:
Var AppView = Backbone. View. extend ({
Template: _. template ("});

In the above Code, the template function of the underscore function library accepts a template string as a parameter and returns the corresponding template function. With this template function, you can generate webpage code by providing specific values.
Copy codeThe Code is as follows:
Var AppView = Backbone. View. extend ({
El: $ ('# iner '),
Template: _. template ("Initialize: function (){
This. render ();
},
Render: function (){
This.cancel.html (this. template ({who: 'World! '}));
}
});

The above code render calls the template method to generate the specific webpage code.

In practical applications, the template is generally placed in the script tag. To prevent the browser from parsing by JavaScript code, set the type attribute to text/template.
Copy codeThe Code is as follows:
<Script type = "text/template" data-name = "templateName">
<! -- Template contents goes here -->
</Script>

You can use the following code to compile the template.
Copy codeThe Code is as follows:
Window. templates = {};
Var $ sources = $ ('script [type = "text/template"] ');
$ Sources. each (function (index, el ){
Var $ el = $ (el );
Templates [$ el. data ('name')] = _.template(cancel.html ());
});

Events attributes

The events attribute is used to specify the view events and their corresponding processing functions.
Copy codeThe Code is as follows:
Var Document = Backbone. View. extend ({
Events :{
"Click. icon": "open ",
"Click. button. edit": "openEditDialog ",
"Click. button. delete": "destroy"
}
});

In the above Code, a click event with three CSS selectors specified and the corresponding three processing functions are provided.

Listento Method

The listento method is used to specify a callback function for a specific event.
Copy codeThe Code is as follows:
Var Document = Backbone. View. extend ({
Initialize: function (){
This. listenTo (this. model, "change", this. render );
}
});

The above code is the change event of the model, and the callback function is specified as render.

Remove Method

The remove method is used to remove a view.
Copy codeThe Code is as follows:
UpdateView: function (){
View. remove ();
View. render ();
};

Subview)

You can call the child view in the parent view. Below is a writing method.
Copy codeThe Code is as follows:
Render: function (){
This.cancel.html (this. template ());
This. child = new Child ();
This. child. appendTo ($. ('. iner-placeholder'). render ();
}

Backbone. Router

The Router is the routing object provided by Backbone. It is used to match the URL of the user request with the backend processing function.

First, define a new Router class.
Copy codeThe Code is as follows:
Router = Backbone. Router. extend ({
Routes :{
}
});

Routes attributes

In the Backbone. Router object, the most important thing is the routes attribute. It is used to set the path processing method.

The routes attribute is an object. Each member of the routes represents a path processing rule. The key name is the path rule and the key value is the processing method.

If the key name is an empty string, it indicates the root path.
Copy codeThe Code is as follows:
Routes :{
'': 'Phonesindex ',
},
PhonesIndex: function (){
New PhonesIndexView ({el: 'section # main '});
}
An asterisk represents any path. You can set path parameters to capture specific path values.
Copy codeThe Code is as follows:
Var AppRouter = Backbone. Router. extend ({
Routes :{
"* Actions": "defaultRoute"
}
});
Var app_router = new AppRouter;
App_router.on ('route: ulultroute ', function (actions ){
Console. log (actions );
})
In the above Code, parameters following the root path will be captured and passed in the callback function.

Path rule syntax.
Copy codeThe Code is as follows:
Var myrouter = Backbone. Router. extend ({
Routes :{
"Help": "help ",
"Search/: query": "search"
},
Help: function (){
...
},
Search: function (query ){
...
}
});
Routes :{
"Help/: page": "help ",
"Download/* path": "download ",
"Folder/: name": "openFolder ",
"Folder/: name-: mode": "openFolder"
}
Router. on ("route: help", function (page ){
...
});

Backbone. history

After setting the router, you can start the application. The Backbone. history object is used to monitor url changes.
Copy codeThe Code is as follows:
App = new Router ();
$ (Document). ready (function (){
Backbone. history. start ({pushState: true });
});

Open the pushState method. If the application is not in the root directory, you must specify the root directory.
Copy codeThe Code is as follows:
Backbone. history. start ({pushState: true, root: "/public/search /"})
Backbone. Model

Model represents a single object entity.
Copy codeThe Code is as follows:
Var User = Backbone. Model. extend ({
Defaults :{
Name :'',
Email :''
}
});
Var user = new User ();

The code above uses the extend method to generate a User class, which represents the model template. Then, use the new command to generate a Model instance. The defaults attribute is used to set the default attribute. The code above indicates that the user object has two attributes by default: name and email. Their values are equal to null strings.

When generating an instance, you can provide the specific values of each attribute.
Copy codeThe Code is as follows:
Var user = new User ({
Id: 1,
Name: 'name ',
Email: 'name @ email.com'
});

The code above provides the specific values of each attribute when generating an instance.

IdAttribute attributes

A Model instance must have an attribute as the primary key to distinguish other instances. The name of this attribute, which is set by the idAttribute attribute, is generally set to id.
Copy codeThe Code is as follows:
Var Music = Backbone. Model. extend ({
Idattri': 'id'
});

Get Method

The get method is used to return the value of an attribute of the Model instance.
Copy codeThe Code is as follows:
Var user = new User ({name: "name", age: 24 });
Var age = user. get ("age"); // 24
Var name = user. get ("name"); // "name"

Set Method

The set method is used to set the value of an attribute of the Model instance.
Copy codeThe Code is as follows:
Var User = Backbone. Model. extend ({
Buy: function (newCarsName ){
This. set ({car: newCarsName });
}
});
Var user = new User ({name: 'bmw ', model: 'i8', type: 'car '});
User. buy ('Porsche ');
Var car = user. get ("car"); // 'Porsche'

On Method

The on method is used to listen for object changes.
Copy codeThe Code is as follows:
Var user = new User ({name: 'bmw ', model: 'i8 '});
User. on ("change: name", function (model ){
Var name = model. get ("name"); // "Porsche"
Console. log ("Changed my car's name to" + name );
});
User. set ({name: 'Porsche '});
// Changed my car's name to Porsche

The on Method in the above code is used to listen for events. "change: name" indicates that the name attribute has changed.

Urlroot attributes

This attribute is used to specify the path for the server to operate on the model.
Copy codeThe Code is as follows:
Var User = Backbone. Model. extend ({
UrlRoot: '/user'
});

The code above specifies that the path of the server pair should be/user.

Fetch event

The fetch event is used to retrieve the Model from the server.
Copy codeThe Code is as follows:
Var user = new User ({id: 1 });
User. fetch ({
Success: function (user ){
Console. log (user. toJSON ());
}
})
In the above Code, the user instance contains the id attribute (with a value of 1). The fetch method uses the HTTP verb GET to send a request to the URL "/user/1" and retrieve the instance from the server.

Save Method

The save method is used to notify the server to create or update a Model.

If a Model instance does not contain the id attribute, the save method uses the POST method to create the instance.
Copy codeThe Code is as follows:
Var User = Backbone. Model. extend ({
UrlRoot: '/user'
});
Var user = new User ();
Var userDetails = {
Name: 'name ',
Email: 'name @ email.com'
};
User. save (userDetails ,{
Success: function (user ){
Console. log (user. toJSON ());
}
})

The code above first specifies the URL of the Model in the class is/user, then creates an instance, and finally calls the save method. It has two parameters. The first parameter is the specific attribute of the instance object, and the second parameter is a callback function object that sets the callback function for the success event (saved successfully. Specifically, the save method sends a POST request to/user and provides {name: 'name', email: 'name @ email.com '} as data.

If a Model instance contains the id attribute, the save method uses the PUT Method to update the instance.
Copy codeThe Code is as follows:
Var user = new User ({
Id: 1,
Name: 'zhang san ',
Email: 'name @ email.com'
});
User. save ({name: 'Li si '},{
Success: function (model ){
Console. log (user. toJSON ());
}
});
In the code above, the object instance contains the id attribute (with a value of 1), save will use the PUT Method to send a request to the URL "/user/1" to update the instance.

Destroy Method

The destroy method is used to delete the instance on the server.
Copy codeThe Code is as follows:
Var user = new User ({
Id: 1,
Name: 'name ',
Email: 'name @ email.com'
});
User. destroy ({
Success: function (){
Console. log ('deststroed ');
}
});

The destroy method in the code above uses the HTTP verb DELETE to send a request to the URL "/user/1" to DELETE the corresponding Model instance.

Backbone. Collection

Collection is a Collection of the same type of Model. For example, a Model is an animal, a Collection is a zoo, a Model is a single person, and a Collection is a company.
Copy codeThe Code is as follows:
Var Song = Backbone. Model. extend ({});
Var Album = Backbone. Collection. extend ({
Model: Song
});

In the code above, Song is Model, Album is Collection, and Album has a model attribute that is equal to Song. Therefore, Album is a Collection of Song.

Add method, remove Method

The Model instance can be directly put into the Collection instance or added using the add method.
Copy codeThe Code is as follows:
Var song1 = new Song ({id: 1, name: "Song name 1", artist: "James "});
Var song2 = new Music ({id: 2, name: "song name 2", artist: "Li Si "});
Var myAlbum = new Album ([song1, song2]);
Var song3 = new Music ({id: 3, name: "song name 3", artist: "Zhao Wu "});
MyAlbum. add (song3 );

The remove method is used to remove a Model instance from the Collection instance.
Copy codeThe Code is as follows:
MyAlbum. remove (1 );

The code above indicates that the parameter of the remove method is the id attribute of the model instance.

Get method, set Method

The get method is used to obtain the Model instance with the specified id from the Collection.
Copy codeThe Code is as follows:
MyAlbum. get (2 ))

Fetch Method

The fetch method is used to retrieve Collection data from the server.
Copy codeThe Code is as follows:
Var songs = new Backbone. Collection;
Songs. url = '/songs ';
Songs. fetch ();

Backbone. events
Copy codeThe Code is as follows:
Var obj = {};
_. Extend (obj, Backbone. Events );
Obj. on ("show-message", function (msg ){
$ ('# Display'). text (msg );
});
Obj. trigger ("show-message", "Hello World ");


Does Javascript have an mvc framework?

You should answer
The MVC model should be available to programmers at any time.
Instead of using other people's frameworks, it cannot be used without frameworks.

What javascript mvc framework can be applied to IE6?

It's strange that javascript-based mvc is just a bit ignorant. Baidu has a bit and Angular is recommended on the Internet. there are a lot of JavaScript files, which were previously written by Google and should be ensured in all aspects ..

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.