認識 Backbone(一) : 什麼是 Model

Backbone 的做者是這樣定義 Model 的:前端

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

那麼,咱們首先來建立一個Modelweb

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

var person = new Person;

上述代碼中,咱們定義了一個名爲 PersonModel,實例化後,獲得 person。任什麼時候候當你實例化一個 Model,都會自動觸發 initialize() 方法(這個原則一樣適用於 collection, view)。固然,定義一個 Model 時,並不是強制要求使用 initialize() 方法,可是隨着你對 Backbone 的使用,你會發現它不可或缺。sql

設置 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 屬性

使用 Modelget() 方法,咱們能夠得到屬性:服務器

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 實例化時自己就包含一些默認的屬性值,這個能夠經過定義 Modeldefaults 屬性來實現:fetch

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 內的屬性。(全部自定義的方法默認爲 publicthis

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 爲例:url

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){});code

服務器與 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,它與服務器端數據一一對應。若是咱們但願在服務器端的 mysqluser 中新增一條記錄,咱們只須要實例化一個 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());
    }
})

此時,在服務器端 mysqluser 表裏多了一條 nameStephenLee,emailstephen.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');
    }
});

參考

http://backbonetutorials.com/what-is-a-model/

相關文章
相關標籤/搜索