JAVASCRIPT MVC Framework Backbone.js detailed _javascript tips

Source: Internet
Author: User
Tags script tag tagname tojson

As JavaScript programs become more complex and often require a team to collaborate on development, the modularity and organizational specifications of the code become extremely important. The MVC pattern is the classic pattern of code organization.

(...... MVC Introduction. )

(1) Model

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

(2) View

View represents the presentation layer, which is the user interface, which is the page HTML code that the user sees.

(3) Controller

Controller represents the control layer, which is used to process the raw data (Model) and transfer it to view.

Since web programming differs from client-side programming, the JavaScript community generates various Variant framework MVP (Model-view-presenter), MVVM (Model-view-viewmodel), and so on, based on MVC, The various models of all such frameworks are collectively referred to as mv*.

The advantage of the framework is that it is reasonable to organize code, to facilitate teamwork and future maintenance, the disadvantage is that there is a certain cost of learning, and limit you can only take it to the wording.

Loading of backbone

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

var Appview = Backbone.View.extend ({
Render:function () {
$ (' main '). Append (' }
});

The above code defines a view class Appview through the Backbone.view extend method. There is a render method inside the class that is used to place the view on a Web page.

When used, you need to create an instance of the view class first, and then invoke the Render method through an instance, so that the view is displayed on the Web page.

Copy Code code as follows:

var appview = new Appview ();
Appview.render ();

The code above creates a new view class Appview instance Appview, and then invokes Appview.render, and the specified content is displayed on the Web page.

When you create a new view instance, you typically need to specify model.

Copy Code code as follows:

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

Initialize method

The view can also define the Initialize method, which is automatically invoked to initialize the instance when the instance is generated.

Copy Code code as follows:

var Appview = Backbone.View.extend ({
Initialize:function () {
This.render ();
},
Render:function () {
$ (' main '). Append (' }
});
var appview = new Appview ();

After the code above defines the Initialize method, it eliminates the steps to manually invoke Appview.render () after the instance is generated.

El Property, $el property

In addition to specifying the page elements that the view is bound to in the Render method, you can also specify a page element with the El property of the view.

Copy Code code as follows:

var Appview = Backbone.View.extend ({
El: $ (' main '),
Render:function () {
this. $el. Append (' }
});

The above code binds the page element directly to the Render method, and the effect is exactly the same. In the code above, in addition to the El attribute, the $el property represents the specified DOM element, which represents the jquery object for that DOM element.

TagName Property, classname Property

If you do not specify an El property, you can also specify it by using the TagName property and the ClassName property.

Copy Code code 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 a page template.

Copy Code code as follows:

var Appview = Backbone.View.extend ({
Template: _.template ("});

In the code above, the underscore function library's template function, which takes a template string as a parameter, returns the corresponding template function. With this template function, the Web page code can be generated as long as you provide a specific value.
Copy Code code as follows:

var Appview = Backbone.View.extend ({
El: $ (' #container '),
Template: _.template ("Initialize:function () {
This.render ();
},
Render:function () {
this. $el. HTML (this.template ({who: ' world! '});
}
});

The render of the above code calls the template method, which generates the specific page code.

In practice, the template is typically placed in the script tag, and the Type property is set to text/template in order to prevent the browser from parsing in JavaScript code.

Copy Code code 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 Code code 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 Property

The Events property is used to specify the event for the view and its corresponding handler function.

Copy Code code as follows:

var Document = Backbone.View.extend ({
Events: {
"Click. Icon": "Open",
"Click. Button.edit": "Openeditdialog",
"Click. Button.delete": "Destroy"
}
});

In the code above, a click event that specifies three CSS selectors, and its corresponding three processing functions.

Listento method

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

Copy Code code as follows:

var Document = Backbone.View.extend ({
Initialize:function () {
This.listento (This.model, "Change", This.render);
}
});

The above code is model's Change event, and the callback function is specified as render.

Remove method

The Remove method is used to remove a view.

Copy Code code as follows:

Updateview:function () {
View.remove ();
View.render ();
};

Child View (Subview)

You can call a child view in the parent view. Here is a way of writing.

Copy Code code as follows:

Render:function () {
this. $el. HTML (this.template ());
This.child = new Child ();
This.child.appendTo ($. ('. Container-placeholder '). Render ();
}

Backbone.router

Router is a backbone-provided routing object that corresponds to the URL of a user's request to the back-end processing function one by one.

First, a new router class is defined.

Copy Code code as follows:

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

Routes Property

The most important thing in the Backbone.router object is the routes attribute. It is used to set the path processing method.

The Routes property is an object in which each member represents a path-handling rule, a key name is a path rule, and a key value is the processing method.

If the key name is an empty string, it represents the root path.

Copy Code code as follows:

Routes: {
': ' Phonesindex ',
},
Phonesindex:function () {
New Phonesindexview ({el: ' Section#main '});
}

The asterisk represents any path, and you can set the path parameters to capture specific path values.
Copy Code code 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 code above, the arguments that follow the root path are captured, passing in the callback function.

The way the path rules are drafted.

Copy Code code as follows:

var myrouter = Backbone.Router.extend ({
Routes: {
' Help ': ' Help ',
"Search/:query": "Search"
},
Help:function () {
...
},
Search:function (query) {
...
}
});
Routes: {
"Help/:p Age": "Help",
"Download/*path": "Download",
"Folder/:name": "Openfolder",
"Folder/:name-:mode": "Openfolder"
}
Router.on ("Route:help", function (page) {
...
});

Backbone.history

After you set up router, you can start the application. The Backbone.history object is used to monitor changes to URLs.

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

Backbone.history.start ({pushstate:true, Root: "/public/search/"})
Backbone.model

Model represents a single object entity.
Copy Code code 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 that represents the model template. Then, use the new command to generate an instance of model. The Defaults property is used to set the default property, which indicates that the user object has the name and email two properties by default, and their values are equal to the empty string.

When you build an instance, you can provide specific values for each property.

Copy Code code as follows:

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

The code above provides a specific value for each property when the instance is generated.

Idattribute Property

The model instance must have a property as a primary key that distinguishes other instances. The name of this property, set by the Idattribute property, is typically set to an ID.

Copy Code code as follows:

var Music = Backbone.Model.extend ({
Idattribute: ' ID '
});

Get method

The Get method is used to return the value of one of the properties of the model instance.

Copy Code code 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 property of the model instance.

Copy Code code 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 to objects.

Copy Code code 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" indicates that the Name property has changed.

UrlRoot Property

This property is used to specify the server-side path to the model operation.

Copy Code code as follows:

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

The code above specifies that the server should/user the path to model.

Fetch Event

The fetch event is used to remove model from the server.

Copy Code code as follows:

var user = new User ({id:1});
User.fetch ({
Success:function (user) {
Console.log (User.tojson ());
}
})

In the code above, the user instance contains an id attribute (a value of 1), and the Fetch method uses an HTTP verb get to send a request to the URL "/user/1" to remove the instance from the server.

Save method

The Save method notifies the server to create a new or updated model.

If a model instance does not contain an id attribute, the Save method creates the new instance using the Post method.

Copy Code code 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 specifies that model's URL in the class is/user, then creates a new instance, and finally calls the Save method. It has two parameters, the first is the specific properties 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 issues a POST request to/user and provides {name: ' name ', email: ' name@email.com '} as data.

If a model instance contains an id attribute, the Save method updates the instance with the Put method.

Copy Code code as follows:

var user = new User ({
Id:1,
Name: ' John ',
Email: ' Name@email.com '
});
User.save ({name: ' Dick '}, {
Success:function (model) {
Console.log (User.tojson ());
}
});

In the code above, the object instance contains an id attribute (a value of 1), and save updates the instance by using the Put method to send a request to the URL "/USER/1".

Destroy method

The Destroy method is used to delete the instance on the server.

Copy Code code as follows:

var user = new User ({
Id:1,
Name: ' Name ',
Email: ' Name@email.com '
});
User.destroy ({
Success:function () {
Console.log (' destroyed ');
}
});

The above code destroy method, will use the HTTP verb delete, sends the request to the URL "/USER/1", deletes the corresponding model instance.

Backbone.collection

Collection is the same type of model set, such as model is an animal, collection is a zoo; model is a single person, collection is a company.

Copy Code code 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 property equal to song, so it shows that album is a collection of song.

Add method, Remove method

The instance of model can be placed directly into an instance of collection, or it can be added using the Add method.

Copy Code code as follows:

var song1 = new Song ({id:1, Name: "Song name 1", Artist: "John"});
var song2 = new Music ({id:2,name: "Song Name 2", Artist: "Dick"});
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 Code code 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 of the specified ID from the collection.

Copy Code code as follows:

Myalbum.get (2))

Fetch method

The Fetch method is used to remove collection data from the server.

Copy Code code as follows:

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

Backbone.events
Copy Code code as follows:

var obj = {};
_.extend (obj, backbone.events);
Obj.on ("Show-message", Function (msg) {
$ (' #display '). Text (msg);
});
Obj.trigger ("Show-message", "Hello World");

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.