Backbone 的作者對 Model 的定位是:任何 Web 應用的核心,承載互動數據以及大部分業務邏輯,例如格式轉換、資料驗證、屬性存取與權限控制。理解 Model 與其集合 Collection,等於掌握了 Backbone 的資料層。
Person = Backbone.Model.extend({
initialize: function(){
alert("Welcome to Backbone!");
}
});
var person = new Person;
每當你建立一個 Model 實例,initialize() 都會被自動呼叫(Collection 與 View 同樣遵循這個規則)。它並非強制實作,但隨著程式碼規模成長,你會發現它幾乎不可或缺——初始化監聽、預設計算通常都放在這裡。
建立實例時可以直接帶入初始屬性,也可以在之後用 set() 補上:
// 建立時直接設定
var person = new Person({ name: "StephenLee", age: 22 });
// 建立後再設定
var person2 = new Person();
person2.set({ name: "StephenLee", age: 22 });
讀取則用 get():
var age = person.get("age"); // 22
var name = person.get("name"); // "StephenLee"
如果希望某個 Model 天生就帶有一組初始值,透過 defaults 宣告即可。實例化時有傳入的值會覆蓋預設值,沒傳入的則沿用預設:
Person = Backbone.Model.extend({
defaults: { name: "LebronJames", age: 30 },
initialize: function(){ alert("Welcome to Backbone!"); }
});
var person = new Person({ name: "StephenLee" });
person.get("age"); // 30(未指定,走預設)
person.get("name"); // "StephenLee"(已被覆蓋)
你可以在 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");
person.get("hobby"); // "coding"
Backbone 為 Model 提供了事件機制,可以針對單一屬性做精細監聽:
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");
alert("Changed my name to " + name);
});
}
});
var person = new Person();
person.set({ name: "KobeBryant" });
若不關心具體哪個屬性,只想在任意屬性變動時收到通知,把事件名換成 "change" 即可:this.on("change", function(model){ ... })。
Model 的另一項職責是承載服務端資料並完成同步。以下假設服務端有一張 user 表,包含 id、name、email 三個欄位,並以 REST 風格透過 /user 對外提供服務。
var UserModel = Backbone.Model.extend({
urlRoot: '/user',
defaults: { name: '', email: '' }
});
每個 Model 都有 id 屬性,用來與服務端記錄一一對應。id 為空意味著這是一條新記錄,此時呼叫 save(),Backbone 會送出 POST 請求:
var user = new UserModel(); // 未指定 id
var userDetails = { name: 'StephenLee', email: 'stephen.lee@mencoplatform.com' };
user.save(userDetails, {
success: function (user) {
alert(user.toJSON());
}
});
服務端收到資料後完成寫入,並把含 id 的結果回傳給 Model。
用已知 id 初始化實例,再呼叫 fetch(),Backbone 會向 /user/1 發出 GET 請求並填入完整記錄:
var user = new UserModel({ id: 1 });
user.fetch({
success: function (user) {
alert(user.toJSON());
}
});
更新時 id 不為空,同樣呼叫 save(),Backbone 會改用 PUT 請求:
var user = new UserModel({ id: 1, name: 'StephenLee', email: 'stephen.lee@mencoplatform.com' });
user.save({ email: 'newemail@qq.com' }, {
success: function (model) {
alert(user.toJSON());
}
});
var user = new UserModel({ id: 1, name: 'StephenLee', email: 'stephen.lee@mencoplatform.com' });
user.destroy({
success: function () {
alert('Destroyed');
}
});
帶著 id 呼叫 destroy(),Backbone 會送出 DELETE 請求,服務端據此刪除對應記錄。
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
// 定義 Model
var Song = Backbone.Model.extend({
defaults: { name: "Not specified", artist: "Not specified" },
initialize: function(){
console.log("Music is the answer");
}
});
// 定義 Collection,並指定其成員型別
var Album = Backbone.Collection.extend({
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]
宣告 model 屬性之後,Collection 便知道該如何把伺服器回傳的原始資料還原成 Model 實例;再加上 Backbone 為 Collection 提供的排序、篩選與批量同步能力,資料層的組織就完整了。