Backbone.js系列教程一 - Backbone.js簡介

來源:互聯網
上載者:User

JavaScript在web應用程式開發前端技術和後端技術的邏輯與運行一塊佔有越來越大的比重.為了協助維護和逐一查看前期邏輯和模組性,MVC模式在近幾年中漸漸普及。其中一種運用廣泛的MVC架構就是Backbone.js。

Backbone中的Models(模型)、Views(視圖)和Controller(控制器)

Backbone.js包含以下幾個主要功能:

  1. 建立模型(以及模型集合);
  2. 建立視圖;
  3. 管理綁定,管理事件兼用不同的模型以及視圖與架構其他部分的聯絡;
  4. 在模型中使用觀察者模式,一旦模型觸發任何change事件,所有顯示此模型資料的視圖接受到該change事件通知,從而自動進行事件重新渲染;
  5. 給DOM處理所依賴的jQuery或Zepto提供支援。

第一部分:模型(Models)

建立模型,首先我們建立一個包含資料的Person對象。

  1. Person = Backbone.Model.extend({
  2. // Person執行個體的建構函式
  3. initialize: function() {
  4. console.log("hello world");
  5. }
  6. });
  7.  
  8. var p = new Person();

很簡單對吧?現在我們為這個Person對象添加一些參數,提供更多的資料,我們添加了姓名和身高屬性。

  1. var p = new Person({name: "Matt", height:"6\"2""});
  2.  
  3. console.log(p.get("name"));

 如果我們不提供姓名和身高時,這個Person對象的這兩個屬性會為空白,因此,我們現在為Person對象提供預設屬性設定。

  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.  
  11. var p = new Person();
  12. p.set({name: "Matt", height: "6"2\""});
  13. console.log(p.get("name"));

 Backbone的綁定功能很強大,當Model資料變化的時候,能夠自動的觸發方法,更新視圖View。

  1. Person = Backbone.Model.extend({
  2. initialize: function() {
  3. console.log("hello world");
  4.  
  5. // 當name屬性改變時,添加一個綁定函數
  6. this.bind("change:name", function() {
  7. console.log(this.get("name") + " is now the value for name");
  8. });
  9. },
  10. defaults: {
  11. name: "Bob Hope",
  12. height: "unknown"
  13. }
  14. });

 我們當然希望Backbone模型中的資料是有效,因此我們添加error,validate方法來確保在建立對象前,資料是有效。

  1. Person = Backbone.Model.extend({
  2. initialize: function() {
  3. console.log("hello world");
  4.  
  5. this.bind("change:name", function() {
  6. console.log(this.get("name") + " is now the value for name");
  7. });
  8.  
  9. // 添加一個和error錯誤綁定的方法,用於處理錯誤資料
  10. this.bind("error", function( model, error ) {
  11. console.error(error);
  12. });
  13. },
  14. defaults: {
  15. name: "Bob Hope",
  16. height: "unknown"
  17. },
  18. validate: function ( attributes ) {
  19. if( attributes.name == "Joe" ) {
  20. // 返回出錯資訊
  21. return "Uh oh, you"re name is Joe!";
  22. }
  23. }
  24. });
  25.  
  26. var person = new Person();
  27. person.set({name: "Joe", height:"6 feet"});
  28.  
  29. console.log(person.toJSON());

 第二部分:視圖(Views)

HTML的樣式:

  1. #container
  2. button Load
  3. ul#list
  4.  
  5. #list-template
  6. li
  7. a(href="")

Backbone 調用:

  1. // 一個簡單的模型
  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.  
  10. var View = Backbone.View.extend({
  11. // 建立建構函式
  12. initialize: function () {
  13. console.log("init");
  14. }
  15. });
  16.  
  17. var view = new View();

 我們從視圖的選項開始:

  1. var View = Backbone.View.extend({
  2. // options --> 提供給建構函式的對象
  3. initialize: function () {
  4. console.log(this.options.blankOption);
  5. }
  6. });
  7.  
  8. var view = new View({ blankOption: "empty string" });
  9. view.blankOption /// 會在console中打出“empty string。

 還有一些特殊預設定的options,el參數允許你將該視圖附加到頁面上已存在的元素。

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

 你還可以建立一個新的元素:

  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.  
  9. var view = new View({ tagName: "div", className: "class", id: "", attributes: "" }); // --> creates a div tag with class "class"

 在這個步驟中,我們要使用一個靜態不變的目標

  1. var View = Backbone.View.extend({
  2. initialize: function () {
  3. console.log(this.el);
  4. },
  5. el: "#container"
  6. });
  7.  
  8. var view = new View({ model: new Links() }); //from first snippet

 然後添加一些事件操作:

  1. var View = Backbone.View.extend({
  2. initialize: function () {
  3. // do nothing
  4. // render() 會調用兩次render
  5. },
  6. el: "#container",
  7. events: {
  8. "click button": "render"
  9. },
  10. render: function() { // 通常這個方法被Backbone調用
  11. var data = this.model.get("data");
  12.  
  13. for (var i=0, l=data.length; i<l; i++){
  14. var li = this.template
  15. .clone()
  16. .find("a")
  17. .attr("href", data[i].href)
  18. .text(data[i].text)
  19. .end();
  20. this.$el // <-- this.$el 是視圖元素的jQuery對象, this.el 是DOM對象
  21. .find("ul#list").append(li);
  22. }
  23. }
  24. });
  25.  
  26. var view = new View({ model: new Links() });

 第三部分:路由器(Router)

路由器提供導航和控制,讓我們發出指令到Web應用程式。添加sub-URLs或標籤就能進行導航,還可以通過連結快速定位應用程式準確的特徵。

  1. var Router = Backbone.Router.extend({
  2. routes: {
  3. // 這個會匹配任何url是符合foo/<param>的,並且提供:bar: 作為參數,傳輸到paramtest方法中
  4. // : 會匹配下一個URI
  5. // 所以#foo/1 會調用paramtest(1)
  6. "foo/:bar" : "paramtest",
  7.  
  8. / * 會匹配全部剩下的URI, 所以 #a/b/c 會調用 func("a/b/c")
  9. "*action" : "func"
  10. },
  11. func: function (action) {
  12. console.log(action);
  13. },
  14. paramtest:function (p) {
  15. console.log(p);
  16. }
  17. });
  18.  
  19. new Router();
  20.  
  21. Backbone.history.start();

第四部分:集合(Collections)

集合提供一種機制將多種執行個體模型組合起來,提供強大的功能特性來維護和收集資料到列表中。

  1. // 這是我們最初的person模型
  2. var Person = Backbone.Model.extend({
  3. // initialize在我們建立Person對象時被調用
  4. initialize: function() {
  5. console.log("Person is initialized.");
  6. },
  7.  
  8. // 預設屬性
  9. defaults: {
  10. name: "undefined",
  11. age: "undefined"
  12. }
  13. });
  14.  
  15. // 建立集合!
  16. var People = Backbone.Collection.extend({
  17. // 當集合被建立時調用
  18. initialize: function() {
  19. console.log("People Collection is initialized");
  20. },
  21.  
  22. // 定義存入集合的資料模型
  23. model: Person
  24. });
  25.  
  26. // 建立一個新的Person對象
  27. var person = new Person({name:"Joe"});
  28.  
  29. // 建立一個集合,然後將Person對象加入這個集合中
  30. var people = new People(person);
  31. people.add([{name:"Bob"}, {name:"Jim"}]);
  32.  
  33. // 在控制台中,打出這個資料模型的資料
  34. console.log(people.toJSON());

於是我們就已經完成了包含了模型和視圖的可用集合。

這是關於Backbone的MVC介紹,在下一篇中,我們會介紹它的具體用法,希望這對大家有所協助。有任何問題,可以留言提問



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.