Backbone Getting Started

Source: Internet
Author: User

A Backbone Introduction

Backbone is a lightweight JavaScript MVC framework that compresses only 23kb, but relies on the two JS libraries of Underscore.js and jquery. Backbone was created by Jeremy Ashkenas, Underscore.js, who also created the elegant JS translation language of Coffeescript.

Model is a key component in backbone, which is used to store all the data of an application, as well as the logic related directly to data manipulation, including data storage, data validation, and triggering related actions when data changes. Whenever a UI action causes changes to the model's properties, the model triggers a change event, and the view that is used to show the state of the model receives feedback, responds accordingly, and redraws the UI. You don't have to write the glue code to update your DOM, for example, to find an element with an element ID and then manipulate it. As soon as the model changes, the view is updated.

Views are used to display data from a model on a page, and to listen to events on the DOM and then respond.

A collection (Collection) is an ordered collection of model objects.

(ii) model

The following three JS files are introduced before using backbone:

<script src= "Https://code.jquery.com/jquery-2.2.0.min.js" ></script>

<script src= "Http://underscorejs.org/underscore-min.js" ></script>

<script src= "Http://backbonejs.org/backbone-min.js" ></script>

1. Create a model

var person = Backbone.Model.extend ({

Initialize:function () {

Alert (' Hello world! ');

}

});

var person = new Person;

A model object person is created and the "Hello world!" is output at initialization time, and then an instance of person object is defined, and executing the above code pops up "Hello world!" on the page The box.

2. Setting the Model property

var person = Backbone.Model.extend ({

Initialize:function () {//instantiation will execute the code here

Alert (' Hello world! ');

}

});

Setting when instantiating a model

var person = new Person ({

Name: ' Jack ',

Age:20

});

can also be set by the set method after the model instantiation

var person = new Person;

Person.set ({

Name: ' Elizabeth ',

Age:18

});

Person.set (' age ', 22);//Set individual properties

Here are three ways to set the model finger: set when instantiated, set multiple properties through the Set method, set a single property by the Set method.

3. Get the Model property

var person = Backbone.Model.extend ({

Initialize:function () {

Console.log (' Hello world! ');

},

Aboutme:function () {

Return ' i\ ' m ' + this.get (' name ') + ', I live in ' + this.get (' address '), street;

}

});

var person = new Person ({

Name: ' Asan ',

Address: {

Street: ' Mongo Street '

}

});

Console.log (Person.aboutme ());

Console.log (Person.get (' name '));

A Aboutme method is defined in model, in which the value of the model property can be obtained by means of the This.get method and returned. An instance of person can call the Aboutme method to output the value of the Model property.

4. Set the Model default property

var person = Backbone.Model.extend ({

Defaults: {//Set default properties

Name: ' Kagol Antony ',

Address: {

Street: ' 1st Street ',

City: ' Shenzhen ',

State: ' TX ',

zipcode:78701

}

},

Initialize:function () {//Initialize, first execute

Console.log (' Hello world! ')

},

Aboutme:function () {

Return ' i\ ' m ' + this.get (' name ') + ', I live in ' + this.get (' address '). Street;

}

});

var person = new Person ({

Name: ' Asan '

});

Console.log (Person.get (' name '));//asan

Console.log (Person.get (' address '). City);//shenzhen

You can set the default property for model by setting the model's Defaults property.

5. Use the Model property

var person = Backbone.Model.extend ({

Defaults: {

Name: ' Kagol Antony ',

Hobby: ' Basketball '

},

Initialize:function () {

Console.log (' Hello world! ')

},

Like:function (hobbyname) {

This.set ({

Hobby:hobbyname

});

}

});

var person = new Person;

Person.like (' coding ');

Console.log (Person.get (' hobby '));

A like method is defined in model, which takes a parameter for the hobby name (Hobbyname), which is used to set the Hobby property.

6. Monitor the change of the model property

var person = Backbone.Model.extend ({

Defaults: {

Name: ' Elizabeth ',

Age:18

},

Initialize:function () {

Console.log (' Hello World ');

This.on (' Change:name ', function (model) {

var name = model.get (' name ');

Console.log (' Changed my name for ' + name);

})

}

});

var person = new Person ({

Name: ' Jack ',

Age:20

}); Changing the Name property when instantiating does not trigger the Change event

Person.set ({name: ' Kagol '});//Trigger Change event, output: ' Changed my name for Kagol '

Console.log (person.haschanged ());//true

Console.log (Person.changedattributes ());//Object {name: "Kagol"}

The Change event is bound by the This.on method at initialization, and can be monitored for changes in a property in the model, in which case the Name property is monitored as long as the name attribute changes to the name of the console output.

7. Data validation

var person = Backbone.Model.extend ({

Validate:function (attributes) {

if (Attributes.age < 0) {

Return ' You can\ ' is negative years old ';

}

},

Initialize:function () {

Console.log (' Hello, world! ');

This.on (' invalid ', function (model, error) {

Console.log (Error);

})

}

});

var person = new Person;

Person.set ({name: ' Mary Poppins ', Age: -21}, {validate:true});//will verify that the output "you can ' t is negative years old"

Person.set ({name: ' Mary Poppins ', age:20}, {validate:true});//Does not validate

Person.set ({name: ' Mary Poppins ', Age: -21}, {validate:false});//Does not validate

Person.set ({name: ' Mary Poppins ', Age:-21});//Does not validate

In the model's validate method, you can define the logic of validation, which accepts a parameter attributes, which represents the model's property, which validates the model's age property and returns a hint of text when it is 0. The invalid method is bound by This.on at initialization time. When setting the model property through the Set method, the second parameter {validate:true} must be taken to validate.

(c) View 1. Loading templates

<script type= "Text/template" id= "Search_template" >

<label>my Search: </label>

<input type= "text" id= "Search_input" >

<input type= "button" id= "Search_button" value= "Search" >

</script>

<div id= "Search_contailer" ></div>

var Searchview = Backbone.View.extend ({

Initialize:function () {

This.render ();

},

Render:function () {

var template = _.template ($ (' #search_template '). HTML (), {});

this. $el. html (template);

}

});

var search_view = new Searchview ({

El: $ (' #search_contailer ')

});

You need to use the Underscore.js Template Library _.template, which can be written on the outside of the view, wrapped in the script tag of type "Text/template", and define a container (here is a div) to hold the contents of the template.

Defining a view is very similar to defining a model, and it also has a initialize method that initializes the Render method (called at initialization) for rendering the template.

2. Adding a listener Event

var Searchview = Backbone.View.extend ({

Initialize:function () {

This.render ();

},

Render:function () {

var template = _.template ($ (' #search_template '). HTML (), {});

this. $el. html (template);

},

Events: {//Add Event

' Click #search_button ': ' Dosearch '

},

Dosearch:function () {

Console.log (' Search for ' + $ (' #search_input '). Val ());

}

});

var search_view = new Searchview ({

El: $ (' #search_contailer ')

});

Adding a listener event can be configured as long as it is configured in the events property of the view, and you can configure multiple events.

3. Passing parameters to the template

<script type= "Text/template" id= "Search_template" >

<label><%= Search_label%></label>

<input type= "text" id= "Search_input" >

<input type= "button" id= "Search_button" value= "Search" >

</script>

<div id= "Search_contailer" ></div>

var Searchview = Backbone.View.extend ({

El: $ (' #search_contailer '),//You can write El directly here

Initialize:function () {

This.render ();

},

Render:function () {

var variables = {//Use template variable

Search_label: ' Kagol Search: '//can pass multiple parameters

};

var template = _.template ($ (' #search_template '). html ());

this. $el. HTML (template (variables));

},

Events: {//Add Event

' Click #search_button ': ' Dosearch '

},

Dosearch:function () {

Console.log (' Search for ' + $ (' #search_input '). Val ());

}

});

var search_view = new Searchview;

To pass parameters in a template, simply pass an object to _.template () ().

(iv) collection (Collection)

<script type= "Text/template" id= "Artist_template" >

<% _.each (Artists, function (artist) {%>

<tr>

<td><%= artist.get (' name ')%></td>

<td><%= artist.get (' hometown ')%></td>

</tr>

<%}); %>

</script>

<table id= "Table" ></table>

var Artist = Backbone.Model.extend ({

Defaults: {

Name: ' Jack ',

Hometown: ' American '

},

Initialize:function () {}

});

var Artists = Backbone.Collection.extend ({

Model:artist

});

var artist1 = new Artist;

var artist2 = new Artist ({

Name: ' Kagol ',

Hometown: ' China '

});

var artist3 = new Artist ({

Name: ' Elizabeth ',

Hometown: ' England '

});

var artists = new Artists ([Artist1, Artist2, Artist3]);

var Artistview = Backbone.View.extend ({

El: $ (' #table '),

Template: _.template ($ (' #artist_template '). html ()),

Initialize:function () {

This.render ();

},

Render:function () {

this. $el. HTML (this.template ({

Artists:artists.models

}));

}

});

var artistview = new Artistview;

In this example, we first create a model called artist, and then define a artist collection named artists. It then defines an instance of three artist and a artists instance, and initializes artists with the instance of the three artist. Then a view is defined and a parameter named artists is defined in the Render method, which is an array, that is, an instance of the artist.

It is important to note that the template uses the Underscore.js _.each for Loop traversal, the first parameter is the parameter artists, and the second parameter is the callback function.

(v) Summary

The most suitable scenario for backbone is a single-page application (SPA), and there is a large number of data models on the page that require complex communication between the models. Backbone in this scenario, it is very good to achieve the inter-module loose coupling and event-driven. Backbone not like angular to help you do a lot of things, you can only under its limited rules to write code, but it is highly customizable, using the tools provided by backbone, you can do anything you want to do.

Backbone Getting Started

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.