首頁 > web前端 > js教程 > 主體

詳解Backbone.js框架中的模型Model與其集合collection_基礎知識

WBOY
發布: 2016-05-16 15:02:13
原創
1553 人瀏覽過

什麼是 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: 'stephen.lee@mencoplatform.com'
};

//因为 model 没有 id 属性,所以此时使用 save() 方法,Backbone 会向服务器端发送一个 POST 请求,服务器端收到数据后,将其存储,并返回包含 id 的信息给 Model
user.save(userDetails, {
  success: function (user) {
    alert(user.toJSON());
  }
})

登入後複製

此時,在伺服器端 mysql 的 user 表裡多了一筆 name 為 StephenLee,email 為 stephen.lee@mencoplatform.com 的記錄。

取得一個 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: 'stephen.lee@mencoplatform.com'
});//实例化时指定 id 值

//因为指定了 id 值,此时使用 save() 方法,Backbone 将会向 user/1 发送 PUT 请求,将会对数据库中 id 为1的记录的 email 修改
user.save({email: 'newemail@qq.com'}, {
  success: function (model) {
    alert(user.toJSON());
  }
});

登入後複製

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

var user = new Usermodel({
  id: 1,
  name: 'StephenLee',
  email: 'stephen.lee@mencoplatform.com'
});//实例化时指定 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]
登入後複製

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!