Backbone.js Series Tutorial One-backbone.js introduction

Source: Internet
Author: User
Tags add empty end extend log string tagname tojson

JavaScript in the Web application development front-end technology and back-end technology logic and run a larger proportion of the share. In order to help maintain and iterate prior logic and modularity, the MVC pattern has become increasingly popular in recent years. One of the widely used MVC frameworks is backbone.js.

Models (model), Views (view) and controller (Controller) in backbone

Backbone.js includes the following key features:

    1. Create models (and model collections);
    2. Create a view;
    3. Manage bindings, manage events with different models and links to other parts of the framework;
    4. Using the Observer pattern in the model, once the model triggers any change events, all views showing the data for this model receive the Change event notification, and the event is automatically rendered again;
    5. Provides support for the jquery or zepto that DOM processing relies on.

Part I.: Model (MODELS)

To create a model, we first create a person object that contains data.

 
  
  
  1. Person = Backbone.Model.extend ({
  2. Constructor for person instance
  3. Console.log ("Hello World");
  4. }
  5. });
  6. var p = new person ();

It's simple, right? Now that we've added some parameters to this person object and provided more data, we've added the name and height attributes.

 
  
  
  1. var p = new Person ({name: "Matt", Height: "6\" 2 "});
  2. Console.log (P.get ("name"));

If we do not provide name and height, the two properties of this person object will be empty, so we now provide the default property settings for the person object.

 
  
  
  1. Person = Backbone.Model.extend ({
  2. Initialize:function () {
  3. Console.log ("Hello World");
  4. },
  5. Defaults: {
  6. Name: "Mark",
  7. Height: "3\" "
  8. }
  9. });
  10. var p = new person ();
  11. P.set ({name: "Matt", Height: "6" 2\ "});
  12. Console.log (P.get ("name"));

Backbone binding function is very powerful, when the Model data changes, can automatically trigger methods, update view views.

 
  
  
  1. Person = Backbone.Model.extend ({
  2. Initialize:function () {
  3. Console.log ("Hello World");
  4. When the Name property changes, add a binding function
  5. This.bind ("Change:name", function () {
  6. Console.log (This.get ("name") + "is now the value for name");
  7. });
  8. },
  9. Defaults: {
  10. Name: "Bob Hope",
  11. Height: "Unknown"
  12. }
  13. });

We certainly want the data in the backbone model to be valid, so we add the Error,validate method to make sure that the data is valid before the object is created.

 
 
  1. Person = Backbone.Model.extend ({
  2. Initialize:function () {
  3. Console.log ("Hello World");
  4. This.bind ("Change:name", function () {
  5. Console.log (This.get ("name") + "is now the value for name");
  6. });
  7. Add a method that is bound to error errors to handle error data
  8. This.bind ("Error", Function (model, error) {
  9. Console.error (Error);
  10. });
  11. },
  12. Defaults: {
  13. Name: "Bob Hope",
  14. Height: "Unknown"
  15. },
  16. Validate:function (attributes) {
  17. if (Attributes.name = = "Joe") {
  18. return error message
  19. Return ' Uh Oh, you ' re name is joe!;
  20. }
  21. }
  22. });
  23. var person = new person ();
  24. Person.set ({name: "Joe", Height: "6 feet"});
  25. Console.log (Person.tojson ());

Part Two: view (views)

Style of HTML:

 
  
  
  1. #container
  2. Button Load
  3. Ul#list
  4. #list-template
  5. Li
  6. A (href= "")

Backbone Call:

 
  
  
  1. A simple model
  2. var Links = Backbone.Model.extend ({
  3. data:[
  4. {text: "Google", href: "http://google.com"},
  5. {text: "Facebook", href: "http://facebook.com"},
  6. {text: "Youtube", href: "http://youtube.com"}
  7. ]
  8. });
  9. var View = Backbone.View.extend ({
  10. Creating constructors
  11. Initialize:function () {
  12. Console.log ("Init");
  13. }
  14. });
  15. var view = new View ();

We start with the options for the view:

 
  
  
  1. var View = Backbone.View.extend ({
  2. Options--> objects provided to constructors
  3. Initialize:function () {
  4. Console.log (this.options.blankOption);
  5. }
  6. });
  7. var view = new View ({blankoption: "empty string"});
  8. View.blankoption///will play "empty string" in the console.

There are also special preset Options,el parameters that allow you to attach the view to elements that already exist on the page.

 
  
  
  1. var View = Backbone.View.extend ({
  2. Initialize:function () {
  3. Console.log (this.options.blankOption);
  4. This.el-> #在DOM中列出
  5. }
  6. });
  7. var view = new View ({el: $ ("#list")});

You can also create a new element:

 
  
  
  1. var View = Backbone.View.extend ({
  2. Initialize:function () {
  3. Console.log (this.options.blankOption);
  4. This.tagname--> Create a "tagName" item in the DOM
  5. $ ("Body"). Append (This.el)
  6. }
  7. });
  8. var view = new View ({tagName: "div", ClassName: "Class", ID: "", Attributes: ""}); --> creates a div tag with class "Class"

In this step, we're going to use a static invariant target

 
  
  
  1. var View = Backbone.View.extend ({
  2. Initialize:function () {
  3. Console.log (This.el);
  4. },
  5. El: "#container"
  6. });
  7. var view = new View ({Model:new Links ()}); From the snippet

Then add some event actions:

 
 
  1. var View = Backbone.View.extend ({
  2. Initialize:function () {
  3. Doing nothing
  4. Render () calls two times render
  5. },
  6. El: "#container",
  7. Events: {
  8. "Click button": "Render"
  9. },
  10. Render:function () {//Usually this method is called by backbone
  11. var data = This.model.get ("Data");
  12. For (Var i=0, l=data.length i<l; i++) {
  13. var li = this.template
  14. . Clone ()
  15. . Find ("a")
  16. . attr ("href", data[i].href)
  17. . Text (Data[i].text)
  18. . end ();
  19. this. $el//<--this. $el is a jquery object for the view element, This.el is a DOM object
  20. . Find ("Ul#list"). Append (LI);
  21. }
  22. }
  23. });
  24. var view = new View ({Model:new Links ()});

Part III: Routers (Router)

The

routers provide navigation and control, and let us send instructions to the Web application. You can navigate by adding sub-urls or labels, and you can quickly locate the exact characteristics of your application by linking.

 
  
  
  1. var Router = Backbone.Router.extend ({
  2. routes: {
  3. //This will match any URL is in accordance with foo/<param> and provide : bar: As a parameter, transferred to the Paramtest method
  4. //: matches the next URI
  5. /So #foo/1 will call Paramtest (1)
  6. "Foo/:bar": "Paramtest",
  7. &NBSP;
  8. "*action": "Func"
  9. Func:function (action) {
  10. Console.log (action);
  11. Paramtest:function (p) {
  12. Console.log (p);
  13. }
  14. });
  15. &NBSP;
  16. new Router ();
  17. &NBSP;
  18. backbone.history.start ();

Part IV: Collection (Collections)

Collections provide a mechanism to combine multiple instance models and provide powerful features to maintain and collect data into the list.

 
 
  1. This is our original person model.
  2. var person = Backbone.Model.extend ({
  3. Initialize is called when we create the person object
  4. Initialize:function () {
  5. Console.log ("person is initialized.");
  6. },
  7. Default Properties
  8. Defaults: {
  9. Name: "Undefined",
  10. Age: "Undefined"
  11. }
  12. });
  13. Create a collection!
  14. var people = Backbone.Collection.extend ({
  15. Called when the collection is created
  16. Initialize:function () {
  17. Console.log ("People Collection is initialized");
  18. },
  19. Define a data model for saving into a collection
  20. Model:person
  21. });
  22. Create a new Person object
  23. var person = new Person ({name: "Joe"});
  24. Create a collection and then add the person object to the collection
  25. var people = new people (person);
  26. People.add ([{name: "Bob"}, {name: "Jim"}]);
  27. In the console, the data for this data model is typed
  28. Console.log (People.tojson ());

So we've finished with the available collections that contain the models and views.

This is about backbone's MVC introduction, in the next article, we will introduce its specific usage, hope this is helpful to everyone. If you have any questions, you can leave a question



Related Article

Beyond APAC's No.1 Cloud

19.6% IaaS Market Share in Asia Pacific - Gartner IT Service report, 2018

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.