Backbone Practical Course (II.)

Source: Internet
Author: User
Tags add filter extend tag name tagname tojson trim unique id

In the backbone real-life tutorial (a) We have written the basic page file, functional requirements and the overall framework. Today we will officially enter the JS code implementation part.

First of all, attach backbone and underscore official document address, here is the best place to study:

backbone:http://backbonejs.org/

underscore:http://underscorejs.org/

The whole example I have done, you can look at here:

Backbone Address Book Instance v1.0

  1. Define the namespace of the project

     var Contact = {      Models: {},      Collections: {},      Views: {}  
  2. A preliminary study of backbone model

    First, the definition of the window model (mainly used in the window part of the page, such as Add, modify contacts, etc.), because the page many places have to use the window, and all of these windows have a lot of similarities, so we define the window as a model for easy management.

     Contact.Models.Dialog = Backbone.Model.extend({      defaults:{          dialogId: "",          title: "",          html: "",          btnvalue: ""      }  

    Defining a model requires inheriting only the backbone model, so that our models have methods and attributes such as get,set,destory, we can rewrite them, or we can define our own methods to manipulate model.

    Defaults: Defines the default properties of the model and the default values for those properties, or you can not define

    Bacbkone is not strictly MVC, so even if we define a dialog model, we can put objects in this model at a later time, such as:

     var tmpDialog = new Contact.Models.Dialog({      aaa : "ssss",      bb: "xxx"  

    At this point, the attributes in Tmpdialog are like this, we can use model.attributes to view all the properties of model:

    At this point we can see that the attributes are:

     {      aaa : "ssss",      bb: "xxx",      dialogId: "",       title: "",       html: "",       btnvalue: ""          

    In addition to these attributes, backbone automatically assigns a unique ID to each model, and can get its value by Model.id.

    When we new a backbone object, we automatically call the Constructor/initialize method, and we can override this method to achieve some effect.

    We can also inherit our model (or view or collection), such as we now need a special window, in addition to the above several attributes, it has special properties and methods, such as:

     Contact.Models.SpecialDialog = Contact.Models.Dialog.extend({      defaults: {          sepcolum: "xxx"      },      sepMethod: function(){          //you codes      }  

    At this time our specialdialog has all the attributes and methods of dialog, and has its own special properties and methods.

    Backbone provides us with a lot of scaffolding, more properties and methods on model please check out the official documentation for backbone.

    The code for the contact model is attached below:

     Contact.Models.Member = Backbone.Model.extend({      defaults:{          name: "",          mobile: "",          email: "",          selected: false      },      //切换选中      toggle: function(){          this.set({              selected: !this.get("selected")          });      }  
  3. A preliminary study of backbone model (collection)

    Collection, as the meaning of the set name. The collection in the backbone is used to store the set of model, or a table in the database, which defines the field of the table. Code on:

     Contact.Collections.Member = Backbone.Collection.extend({ model: Contact.Models.Member, localStorage: new Backbone.LocalStorage("w3cboy-contact"), // 获取已选model selected : function() { return this.filter(function(itm) { return itm.get("selected"); }); }, // 根据关键词搜索 serachByKeyWord:function(keyword){ var pattern = new RegExp($.trim(keyword).toLocaleLowerCase()); return this.filter(function(itm){ var name = itm.get("name").toLocaleLowerCase(), mobile = itm.get("mobile"); return pattern.test(name) pattern.test(mobile); }); } }); 

    Model: defines this collection corresponding model

    The Tosjon method outputs the model object JSON string in collection

    There are two ways to add model to collection:

    1. When created, add

       var member = new Contact.Collections.Member ([{Name: "", Mobile: "", Email: "}, Model2, ...]);  
    2. Add after creation completes

       //多个添加  member.add([model1, model2, ...]);  //单个添加  

      We add when the incoming is a object rather than a model, we do not worry, collection will automatically turn into the corresponding model.

      The filter method is a underscore method in which a list is passed in, and assertions (predicates) are popularly said to judge the filter condition, and return the eligible attributes

      In addition, there are some methods provided by Set,get,remove and underscore, which are used to look carefully at backbone official documents and underscore official documents.

  4. A preliminary study of backbone model (view)

    According to the previous analogy, view is the style of a record in the database (remember that a record, many beginners here is easy to mistake).

    The old rules, the first code:

     Contact.Views.Member = Backbone.View.extend ({tagName: "tr", Template: _.template ($ ("#tmp-memberlist"). html ()), events:{"Click input": "Toggleselect", "click. Contact-edit": "Editmember", "click. Conta          Ct-del ":" Deletemember "}, Initialize:function (opts) {this.mainview = Opts.mainview;          This.listento (This.model, "Change", This.render);      This.listento (This.model, "destroy", This.remove);          }, Render:function () {this. $el. HTML (this.template (This.model.toJSON ()));      return this;          },//Toggle selected Style Toggleselect:function () {this.model.toggle ();      This.mainView.chooseStatus ();          },//Edit contact Editmember:function () {var _this = this; var item = {dialogid: "Editdialog", Title: "Modify Contact", HTML: _.template ($ ("#tmp-membe          R "). HTML (), This.model.toJSON ()), Btnvalue:" Modify "}; _this.mainvIew.dialog.model = new Contact.Models.Dialog (item);          _this.mainview.dialog.render ();          $ ("#subBtn"). Unbind (); $ ("#subBtn"). Bind ("click", Function () {var $name = $ ("#inputName"), $mobile = $ ("#inputMob               Ile "); var name = $.trim ($name. Val ()), mobile = $.trim ($mobile. Val ()), email = $.trim ($ ("#input               Email "). Val ());                  if (!name) {$name. focus ();              return false;                  } if (!mobile) {$mobile. focus ();              return false; } _this.model.set ({name:name, mobile:mobile, Email:ema              Il});          $ ("#editDialog"). Modal ("Hide");      });          ///Remove Contact Deletemember:function () {This.model.destroy ();          Number of contacts this.mainView.totalMembers (); This.mainView.chooseStatus ();     }  });  

    The code in view is relatively complex compared to the front.

    El: Defines what DOM node elements are used to wrap a model, by default using div packages, which are created by Tagname,classname,id, attribute attributes such as:

     tagName: "li",  id: "list",  

    The resulting DOM node would be like this:

    You can also define El directly:

    At this time, the El inside can only fill in the HTML tag name, if the following also defines tagname,id,classname these will not take effect.

    Events: That is, the event, throughout the Model collection view and router, just in front of the model collection is not used, so put it together to speak. If you introduce other libraries, you can also use the event methods provided by other libraries.



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.