Home >Web Front-end >JS Tutorial >Detailed explanation of Javascript MVC framework Backbone.js_javascript skills

Detailed explanation of Javascript MVC framework Backbone.js_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:36:151071browse

As JavaScript programs become more and more complex, they often require a team to collaborate and develop. At this time, the modularization and organization specifications of the code become extremely important. The MVC pattern is the classic pattern of code organization.

(…Introduction to MVC.)

(1)Model

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

(2)View

View represents the presentation layer, which is the user interface. For web pages, it is the HTML code of the web page that the user sees.

(3)Controller

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

Since web programming is different from client programming, based on MVC, the JavaScript community has produced various variant frameworks MVP (Model-View-Presenter), MVVM (Model-View-ViewModel), etc. Some people have All the various modes of this type of framework are collectively called MV*.

The advantage of the framework is that it organizes the code reasonably, facilitates teamwork and future maintenance, but the disadvantage is that it has a certain learning cost and limits you to its writing method.

Backbone loading

Copy code The code is as follows:







Backbone.View

Basic usage

Backbone.View method is used to define the view class.

Copy code The code is as follows:

var AppView = Backbone.View.extend({
render: function(){
$('main').append('

First-level title

');
}
});

The above code defines a view class AppView through the extend method of Backbone.View. There is a render method inside this class that is used to place the view on the web page.

When using it, you need to create a new instance of the view class first, and then call the render method through the instance to display the view on the web page.

Copy code The code is as follows:

var appView = new AppView();
appView.render();

The above code creates a new instance appView of the view class AppView, and then calls appView.render, and the specified content will be displayed on the web page.

When creating a new view instance, you usually need to specify a Model.

Copy code The code is as follows:

var document = new Document({
Model: doc
});

initialize method

Views can also define an initialize method. When an instance is generated, this method will be automatically called to initialize the instance.

Copy code The code is as follows:

var AppView = Backbone.View.extend({
initialize: function(){
This.render();
},
render: function(){
$('main').append('

First-level title

');
}
});
var appView = new AppView();

After the initialize method is defined in the above code, the step of manually calling appView.render() after generating the instance is omitted.

el attribute, $el attribute

In addition to specifying the web page element bound to the "view" directly in the render method, you can also specify the web page element using the el attribute of the view.

Copy code The code is as follows:

var AppView = Backbone.View.extend({
el: $('main'),
render: function(){
This.$el.append('

First-level title

');
}
});

The above code directly binds web page elements to the render method, and the effect is exactly the same. In the above code, in addition to the el attribute, there is also the $el attribute. The former represents the specified DOM element, and the latter represents the jQuery object corresponding to the DOM element.

tagName attribute, className attribute

If the el attribute is not specified, it can also be specified through the tagName attribute and className attribute.

Copy code The 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 the web page template.

Copy code The code is as follows:

var AppView = Backbone.View.extend({
Template: _.template("

Hello <%= who %>

"),
});


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, web page code can be generated as long as specific values ​​are provided.
Copy code The code is as follows:

var AppView = Backbone.View.extend({
      el: $('#container'),
Template: _.template("

Hello <%= who %>

"),
initialize: function(){
This.render();
},
       render: function(){
This.$el.html(this.template({who: 'world!'}));
}
});


The render of the above code calls the template method to generate specific web page code.

In actual application, the template is generally placed in the script tag. In order to prevent the browser from parsing according to the JavaScript code, the type attribute is set to text/template.

Copy code The code is as follows:



The template can be compiled using the code below.
Copy code The 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($el.html());
});

events attribute

The events attribute is used to specify the events of the view and their corresponding processing functions.

Copy code The 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 specifies three CSS selectors and their corresponding three handlers.

listento method

The listento method is used to specify a callback function for a specific event.

Copy code The 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 code The code is as follows:

updateView: function() {
view.remove();
view.render();
};

Subview

Subviews can be called in parent views. Here is one way to write it.

Copy code The code is as follows:

render : function (){
This.$el.html(this.template());
This.child = new Child();
This.child.appendTo($.('.container-placeholder').render();
}

Backbone.Router

Router is a routing object provided by Backbone, which is used to one-to-one correspondence between the URL requested by the user and the back-end processing function.

First, define a new Router class.

Copy code The code is as follows:

Router = Backbone.Router.extend({
Routes: {
}
});

routes attribute

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, and each member of it 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 represents the root path.

Copy code The code is as follows:

routes: {
          '': 'phonesIndex',
},
phonesIndex: function () {
new PhonesIndexView({ el: 'section#main' });
}

The asterisk represents any path, and path parameters can be set to capture specific path values.
Copy code The code is as follows:

var AppRouter = Backbone.Router.extend({
Routes: {
"*actions": "defaultRoute"
}
});
var app_router = new AppRouter;
app_router.on('route:defaultRoute', function(actions) {
console.log(actions);
})

In the above code, the parameters after the root path will be captured and passed into the callback function.

How to write path rules.

Copy code The code is as follows:

var myrouter = Backbone.Router.extend({
routes: {
"help": "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 up the router, you can start the application. The Backbone.history object is used to monitor URL changes.

Copy code The 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 need to specify the root directory.
Copy code The code is as follows:

Backbone.history.start({pushState: true, root: "/public/search/"})
Backbone.Model

Model represents a single object entity.
Copy code The code is as follows:

var User = Backbone.Model.extend({
           defaults: {
name: '',
Email: ''
}
});
var user = new User();

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

When generating an instance, you can provide specific values ​​for each attribute.

Copy code The code is as follows:

var user = new User ({
id: 1,
name: 'name',
Email: 'name@email.com'
});

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

idAttribute attribute

Model instances must have an attribute that serves as the primary key to distinguish other instances. The name of this attribute is set by the idAttribute attribute, usually set to id.

Copy code The code is as follows:

var Music = Backbone.Model.extend({
idAttribute: 'id'
});

get method

The get method is used to return the value of a certain attribute of the Model instance.

Copy code The 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 a certain attribute of the Model instance.

Copy code The 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 monitor changes in objects.

Copy code The 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 attribute

This attribute is used to specify the path to operate the model on the server side.

Copy code The code is as follows:

var User = Backbone.Model.extend({
urlRoot: '/user'
});

The above code specifies that the path of the server corresponding to the Model is /user.

fetch event

The fetch event is used to retrieve the Model from the server.

Copy code The 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 (value is 1), and the fetch method uses the HTTP verb GET to make a request to the URL "/user/1" to 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 an id attribute, the save method will use the POST method to create a new instance.

Copy code The 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 above code first specifies that the URL corresponding to the Model is /user in the class, then creates a new instance, and finally calls the save method. It has two parameters, the first 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 (save successfully). Specifically, the save method will make a POST request to /user and provide {name: ‘name’, email: ‘name@email.com’} as data.

If a Model instance contains an id attribute, the save method will use the PUT method to update the instance.

Copy code The code is as follows:

var user = new User ({
id: 1,
Name: '张三',
Email: 'name@email.com'
});
user.save({name: '李思'}, {
Success: function (model) {
console.log(user.toJSON());
}
});

In the above code, the object instance contains the id attribute (the value is 1), and save will use the PUT method to make 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 code The code is as follows:

var user = new User ({
id: 1,
name: 'name',
Email: 'name@email.com'
});
user.destroy({
Success: function () {
console.log('Destroyed');
}
});

The destroy method of the above code will use the HTTP verb DELETE to make a request to the URL "/user/1" to delete the corresponding Model instance.

Backbone.Collection

Collection is a collection of Models of the same type. For example, Model is an animal, and Collection is a zoo; Model is a single person, and Collection is a company.

Copy code The code is as follows:

var Song = Backbone.Model.extend({});
var Album = Backbone.Collection.extend({
Model: Song
});

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

add method, remove method

Model instances can be directly placed into Collection instances, or added using the add method.

Copy code The code is as follows:

var song1 = new Song({ id: 1 ,name: "歌名1", artist: "张三" });
var song2 = new Music ({id: 2,name: "歌名2", artist: "李思" });
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 a Collection instance.
Copy code The code is as follows:

myAlbum.remove(1);

The above code shows 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 code The code is as follows:

myAlbum.get(2))

fetch method

The fetch method is used to retrieve Collection data from the server.

Copy code The code is as follows:

var songs = new Backbone.Collection;
songs.url = '/songs';
songs.fetch();

Backbone.events
Copy code The 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");
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn