As JavaScript programs become more and more complex, they often require a team to develop in collaboration, and the modularization of the code and organizational specifications become extremely important. The MVC pattern is a classic model of code organization.
(…Introduction to MVC.)
(1) Model
Model represents the data layer, that is, the data source required by the program, and is usually represented 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 seen by users.
(3) Controller
Controller represents the control layer, used to process the original data (Model) and transfer 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 collectively call all the various modes of this type of framework MV*.
The advantage of a framework is that it organizes code reasonably, facilitates teamwork and future maintenance, and the disadvantage is that it has a certain learning cost and limits you to write it.
Backbone loading
The code copy 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 a view class.
The code copy is as follows:
var AppView = Backbone.View.extend({
render: function(){
$('main').append('<h1>First-level title</h1>');
}
});
The above code defines a view class AppView through the extend method of Backbone.View. There is a render method inside this class to place the view on the web page.
When using it, you need to create a new instance of the view class, and then call the render method through the instance, so that the view can be displayed on the web page.
The code copy is as follows:
var appView = new AppView();
appView.render();
The above code creates a new instance appView of the view class AppView, and then call 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.
The code copy is as follows:
var document = new Document({
model: doc
});
Initialize method
The view can also define the initialize method. When generating an instance, the method will be automatically called to initialize the instance.
The code copy is as follows:
var AppView = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
$('main').append('<h1>First-level title</h1>');
}
});
var appView = new AppView();
After the above code defines the initialize method, it eliminates the step of manually calling appView.render() after generating the instance.
el attribute, $el attribute
In addition to specifying the web page element bound to "view" directly in the render method, you can also specify the web page element using the el attribute of the view.
The code copy is as follows:
var AppView = Backbone.View.extend({
el: $('main'),
render: function(){
this.$el.append('<h1>First-level title</h1>');
}
});
The above code directly binds web page elements with the render method, and the effect is exactly the same. In the above code, in addition to the el attribute, it 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 the className attribute.
The code copy is as follows:
var Document = Backbone.View.extend({
tagName: "li",
className: "document",
render: function() {
// ...
}
});
template method
The template property of the view is used to specify the web page template.
The code copy is as follows:
var AppView = Backbone.View.extend({
template: _.template("<h3>Hello <%= who %><h3>"),
});
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, as long as the specific value is provided, the web page code can be generated.
The code copy is as follows:
var AppView = Backbone.View.extend({
el: $('#container'),
template: _.template("<h3>Hello <%= who %><h3>"),
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 practical applications, templates are generally placed in script tags. In order to prevent browsers from parsing according to JavaScript code, the type attribute is set to text/template.
The code copy is as follows:
<script type="text/template" data-name="templateName">
<!-- template contents go here -->
</script>
You can use the following code to compile the template.
The code copy 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 event of the view and its corresponding handling functions.
The code copy is as follows:
var Document = Backbone.View.extend({
events: {
"click .icon": "open",
"click .button.edit": "openEditDialog",
"click .button.delete": "destroy"
}
});
One of the above code specifies the click event of three CSS selectors and its corresponding three handling functions.
listento method
The listento method is used to specify a callback function for a specific event.
The code copy 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.
The code copy is as follows:
updateView: function() {
view.remove();
view.render();
};
Subview
The child view can be called in the parent view. The following is a way of writing.
The code copy 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 correspond to the URL requested by the user with the backend processing function one by one.
First, a new Router class is defined.
The code copy is as follows:
Router = Backbone.Router.extend({
routes: {
}
});
routes attribute
The most important thing in the Backbone.Router object is the routes property. 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.
The code copy is as follows:
routes: {
'': 'phonesIndex',
},
phonesIndex: function () {
new PhonesIndexView({ el: 'section#main' });
}
An asterisk represents any path, and you can set the path parameters to capture the specific path values.
The code copy 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 behind the root path will be captured and the callback function will be passed into.
How to write path rules.
The code copy 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 up the router, you can start the application. The Backbone.history object is used to monitor changes in urls.
The code copy 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.
The code copy is as follows:
Backbone.history.start({pushState: true, root: "/public/search/"})
Backbone.Model
Model represents a single object entity.
The code copy 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 the Model. The defaults attribute is used to set the default attribute. The above code indicates that the user object has two attributes name and email by default, and their values are equal to an empty string.
When generating an instance, you can provide specific values for each attribute.
The code copy is as follows:
var user = new User ({
id: 1,
name: 'name',
email: '[email protected]'
});
The above code provides the specific values of each attribute when generating an instance.
idAttribute attribute
Model instances must have a property that serves as the primary key to distinguish other instances. The name of this attribute is set by the idAttribute attribute, and is generally set to id.
The code copy is as follows:
var Music = Backbone.Model.extend({
idAttribute: 'id'
});
get method
The get method is used to return the value of a certain property of the Model instance.
The code copy 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 property of the Model instance.
The code copy 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 changes in objects.
The code copy 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, and "change:name" means that the name attribute has changed.
urlroot attributes
This property is used to specify the path to operate on the model on the server side.
The code copy is as follows:
var User = Backbone.Model.extend({
urlRoot: '/user'
});
The above code specifies that the path to the server corresponding to the Model is /user.
fetch event
The fetch event is used to fetch the Model from the server.
The code copy 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). The fetch method uses the HTTP verb GET to issue a request to the URL "/user/1" and retrieves the instance from the server.
Save method
The save method is used to notify the server to create or update the model.
If a Model instance does not contain an id attribute, the save method will create the instance using the POST method.
The code copy is as follows:
var User = Backbone.Model.extend({
urlRoot: '/user'
});
var user = new User ();
var userDetails = {
name: 'name',
email: '[email protected]'
};
user.save(userDetails, {
success: function (user) {
console.log(user.toJSON());
}
})
The above code first specifies that the corresponding URL of Model is /user in the class, then create a new instance, and finally call the save method. It has two parameters. The first is the specific attribute of the instance object, and the second is a callback function object, which sets the callback function for the success event (save successfully). Specifically, the save method will issue a POST request to /user and provide {name: 'name', email: '[email protected]'} as data.
If a Model instance contains an id attribute, the save method will update the instance using the PUT method.
The code copy is as follows:
var user = new User ({
id: 1,
name: 'Zhang San',
email: '[email protected]'
});
user.save({name: 'Li Si'}, {
success: function (model) {
console.log(user.toJSON());
}
});
In the above code, the object instance contains an id attribute (value is 1), 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.
The code copy is as follows:
var user = new User ({
id: 1,
name: 'name',
email: '[email protected]'
});
user.destroy({
success: function () {
console.log('Destroyed');
}
});
The destroy method in the above code will use the HTTP verb DELETE to issue a request to the URL "/user/1" and delete the corresponding Model instance.
Backbone.Collection
Collection is a collection of the same type of models. For example, Model is an animal, Collection is a zoo; Model is a single person, Collection is a company.
The code copy is as follows:
var Song = Backbone.Model.extend({});
var Album = Backbone.Collection.extend({
model: Song
});
In the above code, Song is Model, Album is Collection, and Album has a model attribute equal to Song, so it means that Album is a collection of Song.
add method, remove method
The Model instance can be placed directly into the Collection instance, or added using the add method.
The code copy is as follows:
var song1 = new Song({ id: 1 ,name: "Song Title 1", artist: "Zhang San" });
var song2 = new Music ({id: 2,name: "Song Title 2", artist: "Li Si" });
var myAlbum = new Album([song1, song2]);
var song3 = new Music({ id: 3, name: "Song Title 3",artist:"Zhao Wu" });
myAlbum.add(song3);
The remove method is used to remove a Model instance from the Collection instance.
The code copy 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 get the Model instance of the specified id from the Collection.
The code copy is as follows:
myAlbum.get(2))
fetch method
The fetch method is used to fetch Collection data from the server.
The code copy is as follows:
var songs = new Backbone.Collection;
songs.url = '/songs';
songs.fetch();
Backbone.events
The code copy is as follows:
var obj = {};
_.extend(obj, Backbone.Events);
obj.on("show-message", function(msg) {
$('#display').text(msg);
});
obj.trigger("show-message", "Hello World");