DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> JavaScript基礎知識 >> 詳解Backbone.js框架中的模型Model與其集合collection
詳解Backbone.js框架中的模型Model與其集合collection
編輯:JavaScript基礎知識     

什麼是 Model
Backbone 的作者是這樣定義 Model 的:

Model 是任何一個 web 應用的核心,它包含了交互的數據以及大部分的邏輯。例如:轉化、驗證、屬性和訪問權限等。
那麼,我們首先來創建一個Model:

Person = Backbone.Model.extend({
  initialize: function(){
    alert("Welcome to Backbone!");
  }
});

var person = new Person;

上述代碼中,我們定義了一個名為 Person 的 Model,實例化後,得到 person。任何時候當你實例化一個 Model,都會自動觸發 initialize() 方法(這個原則同樣適用於 collection, view)。當然,定義一個 Model 時,並非強制要求使用 initialize() 方法,但是隨著你對 Backbone 的使用,你會發現它不可或缺。

設置 Model 屬性
現在我們想在創建 Model 實例時傳遞一些參數用來設置 Model 的屬性:

Person = Backbone.Model.extend({
  initialize: function(){
    alert("Welcome to Backbone!");
  }
});

//在實例化 Model 時直接設置
var person = new Person({ name: "StephenLee", age: 22 });

//我們也可以在 Model 實例化後,通過 set() 方法進行設置
var person = new Person();
person.set({ name: "StephenLee", age: 22});

獲得 Model 屬性
使用 Model 的 get() 方法,我們可以獲得屬性:

Person = Backbone.Model.extend({
  initialize: function(){
    alert("Welcome to Backbone!");
  }
});

var person = new Person({ name: "StephenLee", age: 22});

var age = person.get("age"); // 22
var name = person.get("name"); // "StephenLee"

設置 Model 默認屬性
有時你希望 Model 實例化時本身就包含一些默認的屬性值,這個可以通過定義 Model 的 defaults 屬性來實現:

Person = Backbone.Model.extend({
  defaults: {
    name: "LebronJames",
    age: 30,
  },
  initialize: function(){
    alert("Welcome to Backbone!");
  }
});

var person = new Person({ name: "StephenLee"});

var age = person.get("age"); // 因為實例化時未指定 age 值,則為默認值 30
var name = person.get("name"); //實例化制定了 name 值,則為 "StephenLee"

使用 Model 屬性
你可以在 Model 中自定義方法來使用 Model 內的屬性。(所有自定義的方法默認為 public)

Person = Backbone.Model.extend({
  defaults: {
    name: "LebronJames",
    age: 30,
    hobby: "basketball"
  },
  initialize: function(){
    alert("Welcome to Backbone!");
  },
  like: function( hobbyName ){
    this.set({ hobby: hobbyName });
  },
});

var person = new Person({ name: "StephenLee", age: 22});

person.like("coding");// 設置 StephenLee's hobby 為 coding
var hobby = person.get("hobby"); // "coding"

監聽 Model 屬性的改變
根據 Backbone 的機制,我們可以給對 Model 的任意屬性進行監聽,接下來,我們嘗試在 initialize() 方法中綁定 Model 一個的屬性進行監聽,以屬性 name 為例:

Person = Backbone.Model.extend({
  defaults: {
    name: "LebronJames",
    age: 30,
  },
  initialize: function(){
    alert("Welcome to Backbone!");
    this.on("change:name", function(model){
      var name = model.get("name"); // 'KobeBryant'
      alert("Changed my name to " + name );
    });
  }
});

var person = new Person();

var age = person.set({name : "KobeBryant"});

通過上述代碼,我們知道了如何對 Model 的某個屬性進行監聽。假設我們需要對 Model 所有的屬性進行監聽,則使用 'this.on("change", function(model){}); 。

服務器與 Model 的數據交互
前文中已提到 Model 包含了交互的數據,所以它的作用之一便是承載服務器端傳來的數據,並與服務器端進行數據交互。現在我們假設服務器端有一個 mysql 的表 user,該表有三個字段 id, name, email 。服務器端采用 REST 風格與前端進行通信,使用 URL:/user 來進行交互。我們的 Model 定義為:

var UserModel = Backbone.Model.extend({
  urlRoot: '/user',
  defaults: {
    name: '',
    email: ''
  }
});

創建一個 Model
Backbone 中每個 Model 都擁有一個屬性 id,它與服務器端數據一一對應。如果我們希望在服務器端的 mysql 表 user 中新增一條記錄,我們只需要實例化一個 Model,然後調用 save() 方法即可。此時 Model 實例的屬性 id 為空,即說明這個 Model 是新建的,因此 Backbone 將會向指定的 URL 發送一個 POST 請求。

var UserModel = Backbone.Model.extend({
  urlRoot: '/user',
  defaults: {
    name: '',
    email: ''
  }
});

var user = new Usermodel();
//注意,我們並沒有在此定義 id 屬性
var userDetails = {
  name: 'StephenLee',
  email: '[email protected]'
};

//因為 model 沒有 id 屬性,所以此時使用 save() 方法,Backbone 會向服務器端發送一個 POST 請求,服務器端收到數據後,將其存儲,並返回包含 id 的信息給 Model
user.save(userDetails, {
  success: function (user) {
    alert(user.toJSON());
  }
})

此時,在服務器端 mysql 的 user 表裡多了一條 name 為 StephenLee,email 為 [email protected] 的記錄。

取得一個 Model
剛剛我們已經創建了一個 Model,並將它存儲到了服務器端的數據庫中,假設創建 Model 時,服務器端返回的 id 屬性值為 1,此時,我們通過 id 的值就可以將已存儲的數據取回。當我們用 id 屬性值初始化一個 Model 實例時,通過 fetch() 操作,Backbone 將會向指定的 URL 發送一個 GET 請求。

var user = new Usermodel({id: 1});//初始化時指定 id 的值

//利用 fetch() 方法將會向 user/1 請求數據,服務器端將會返回完整的 user 記錄,包含 name,email 等信息
user.fetch({
  success: function (user) {
    alert(user.toJSON());
  }
})

更新一個 Model
如果我們需要對已經存儲的 user 記錄進行修改,利用已知的 id 值,同樣使用 save() 方法,但因為此時 id 不為空,Backbone 將會向指定的 URL 發送一個 PUT 請求。

var user = new Usermodel({
  id: 1,
  name: 'StephenLee',
  email: '[email protected]'
});//實例化時指定 id 值

//因為指定了 id 值,此時使用 save() 方法,Backbone 將會向 user/1 發送 PUT 請求,將會對數據庫中 id 為1的記錄的 email 修改
user.save({email: '[email protected]'}, {
  success: function (model) {
    alert(user.toJSON());
  }
});

刪除一個 Model
如果我們需要刪除數據庫中的記錄,利用已知的 id 值,使用 destroy() 方法即可。此時,Backbone 將會向指定的 URL 發送一個 DELETE 操作。

var user = new Usermodel({
  id: 1,
  name: 'StephenLee',
  email: '[email protected]'
});//實例化時指定 id 值

//因為指定了 id 值,此時使用 destroy() 方法,Backbone 將會向 user/1 發送 DELETE 請求,服務器端接收請求後,將會在數據庫中刪除 id 為 1的數據
user.destroy({
  success: function () {
    alert('Destroyed');
  }
});

什麼是 Collection
簡而言之,Backbone 中的 Collection 就是 Model 的一個有序集合,比如,它可能會在以下情況中用到:

Model: Student, Collection: ClassStudents
Model: Todo Item, Collection: Todo List
Model: Animal, Collection: Zoo

Collection 一般只使用同一類型的 Model,但是 Model 可以屬於不同類型的 Collection,比如:

Model: Student, Collection: Gym Class
Model: Student, Collection: Art Class
Model: Student, Collection: English Class

創建一個 Collection

//定義 Model Song
var Song = Backbone.Model.extend({
  defaults: {
    name: "Not specified",
    artist: "Not specified"
  },
  initialize: function(){
    console.log("Music is the answer");
  }
});

//定義 Collection Album
var Album = Backbone.Collection.extend({
  model: Song //指定 Collection 內的 Model 為 Song
});

var song1 = new Song({ name: "How Bizarre", artist: "OMC" });
var song2 = new Song({ name: "Sexual Healing", artist: "Marvin Gaye" });
var song3 = new Song({ name: "Talk It Over In Bed", artist: "OMC" });

var myAlbum = new Album([ song1, song2, song3]);
console.log( myAlbum.models ); // 輸出為 [song1, song2, song3]

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved