DIV CSS 佈局教程網

Backbone.js 中 Model 與 View 的原始碼解析
編輯:JavaScript基礎知識     

Backbone.Model

Model 是 Backbone 的核心部分,承載著頁面展示所需的資料,以及圍繞資料的各種轉換、校驗、計算、權限控制、伺服器互動等操作。你可以透過 Backbone.Model.extend() 產生自己的 model,產生的 model 也可以作為基類繼續向下擴展。

var People = Backbone.Model.extend({});
var Man = People.extend({});

Backbone.Model 提供了大量方法來實現 Model 的基本操作,其中最基礎的是基於 Backbone.Events 的事件機制——當 Model 的 attributes 發生變化時,相應的 change:attr 事件會被觸發。

其中與伺服器操作相關的方法:

  • sync:包裝了 Backbone.sync,是 xhr 的基類
  • fetch:從伺服器獲取資料
  • save:向伺服器持久化資料
  • destroy:從伺服器刪除資料

資料操作方法:

  • get:從 attributes 中獲取資料
  • set:向 attributes 中設定資料
  • escape:對資料進行編碼,使用 underscore 的 _.escape
  • has:判斷 attributes 中是否有對應資料
  • unset:從 attributes 中刪除資料
  • clear:清空 attributes
  • toJSON:把 attributes 序列化成一個物件
  • previous/previousAttributes:取得前一次狀態的資料

資料校驗方法:

  • validate:對 model 中的資料進行校驗,需重寫覆蓋預設方法
  • isValid:呼叫 _validate 方法

構造函式

var Model = Backbone.Model = function(attributes, options) {
  var attrs = attributes || {};
  options || (options = {});
  this.cid = _.uniqueId('c');
  this.attributes = {};
  if (options.collection) this.collection = options.collection;
  if (options.parse) attrs = this.parse(attrs, options) || {};
  attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
  this.set(attrs, options);
  this.changed = {};
  this.initialize.apply(this, arguments);
};

構造函式主要對初始資料和選項進行設定,並產生一個唯一的 cid 用於標示 model;若 options 中的 parse 為 true,會先對初始值進行 parse 解析,接著呼叫 set 把所有初始值存入 attributes,最後呼叫 initialize 完成初始化。

set

set 方法會把值設定進 attributes。它的整個流程是:把傳入值處理成鍵值對 → 校驗資料正確性 → 檢查值是否發生改變(有則加入 changed 物件)→ 根據 unset 進行新增、更新或刪除 → 依序觸發 change:attr 與 change 事件。

save

save 方法用於向伺服器持久化資料,會根據資料與配置選擇使用 create、update 或 patch,並觸發 sync 事件。其中最需要注意的是 wait 設定:當 wait 為 true 時,save 會等到 xhr 返回之後才執行 set,而非在請求之前就 set,因此 change 事件的觸發時機也随之不同。

整個 Backbone 都是透過事件串聯起來的,因此對事件觸發時機的理解與把握非常重要,否則容易在開發中遇到各種怪問題。

Backbone.View

View 主要用於溝通頁面中的 DOM 與 Backbone.Model/Collection,處理頁面邏輯與 DOM 事件綁定。View 部分的程式碼非常簡潔,加上註解也不過 110 行左右。

構造方法

var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
var View = Backbone.View = function(options) {
  this.cid = _.uniqueId('view');
  options || (options = {});
  _.extend(this, _.pick(options, viewOptions));
  this._ensureElement();
  this.initialize.apply(this, arguments);
  this.delegateEvents();
};

構造方法中為 View 產生一個以 'view' 開頭的唯一 cid,合併 viewOptions 屬性,接著呼叫 _ensureElement 判斷 el 的情況,再呼叫 delegateEvents 進行事件綁定,初始化完成。

_ensureElement

_ensureElement: function() {
  // 如果已經對 el 進行設置,直接調用 setElement
  if (!this.el) {
    var attrs = _.extend({}, _.result(this, 'attributes'));
    if (this.id) attrs.id = _.result(this, 'id');
    if (this.className) attrs['class'] = _.result(this, 'className');
    var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
    this.setElement($el, false);
  } else {
    this.setElement(_.result(this, 'el'), false);
  }
}

這個內部方法在構造函式中使用,用於判斷指定的 el 是否存在於頁面中:若存在則對 $el 賦值;若不存在則生成一個 $el(但這個物件尚未落地到 DOM 樹中)。

delegateEvents

delegateEvents: function(events) {
  if (!(events || (events = _.result(this, 'events')))) return this;
  this.undelegateEvents();  // 先解除所有事件綁定
  for (var key in events) {
    var method = events[key];
    if (!_.isFunction(method)) method = this[events[key]];
    if (!method) continue;
    var match = key.match(delegateEventSplitter);
    var eventName = match[1], selector = match[2];
    method = _.bind(method, this);
    eventName += '.delegateEvents' + this.cid;
    if (selector === '') {
      this.$el.on(eventName, method);
    } else {
      this.$el.on(eventName, selector, method);
    }
  }
  return this;
}

在 View 中你可以用 key:value 集合指定事件,初始化時構造函式會呼叫 delegateEvents 進行綁定。需要注意的是,key 中選擇器的父元素必須是 $el(即元素必須是 $el 的子節點),否則綁定失敗。

View 與其他 Backbone 模組的一個區別,是它沒有自己的內建自訂事件;雖然它也組合了 Events 模組,但所有事件都需要自己建立。View 主要是一個 MVC 模型的承載,真正的功能不多,絕大部分邏輯都需要開發者自行擴展。

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