DIV CSS 佈局教程網

用 JavaScript 對 JSON 做模式匹配(Part 2-實作)
編輯:關於JavaScript     

Notify 與 Capture

要實作 notify 和 capture 其實很簡單:把 capture 傳入的 handler 都存起來,notify 時找出匹配的 handler 執行即可。

var filterHandlerBundles = [];
Dispatch.capture = function (pattern, handler) {
  var filter = createFilter(pattern);
  filterHandlerBundles.push({
    "filter": filter,
    "handler": handler
  });
};
Dispatcher.notify = function (json) {
  for (var i = 0; i < filterHandlerBundles.length; i++) {
    if (filterHandlerBundles[i].filter.apply(this, arguments)) {
      filterHandlerBundles[i].handler(json);
    }
  }
};

關鍵在於 createFilter——它負責把描述模式的 JSON 轉換成一個判斷是否匹配的函數。

運算子的實作

我們設計了不少運算子,如何實作?記住不要用 switch case,改用關聯陣列保存運算子與實作的對應關係:

var operators = {};
operators["lt"] = function (testValue, value) {
  return arguments.length == 2 && value < testValue;
};
operators["lte"] = function (testValue, value) {
  return arguments.length == 2 && value <= testValue;
};
operators["gt"] = function (testValue, value) {
  return arguments.length == 2 && value > testValue;
};
operators["gte"] = function (testValue, value) {
  return arguments.length == 2 && value >= testValue;
};

如此只要把 "$" 後面的運算子抽出來,就能立刻找到對應的判斷函數。比較麻煩的是 eq,因為它得依資料型別選擇判斷方式:String、Number、Boolean 用 ==;Array 則要求每個元素都 eq 且順序一致;Object 則要求每個子條件都符合。

其他運算子的提示如下,讀者可依需求實作子集或超集:

in-遍歷陣列,看是否至少能找到一個 eq 的;all-遍歷陣列,看是否每一個都存在 eq 的;ex-若有傳入值,則子元素存在;re-用正則表達式判斷字串是否匹配;ld-直接呼叫函數進行判斷。

寫好之後,先加上一個預設運算子:

operators[""] = function (testValue, value) {
  if (testValue instanceof Array) {
    return operators["in"].apply(this, arguments);
  } else if (testValue instanceof RegExp) {
    return operators["re"].apply(this, arguments);
  } else if (testValue instanceof Function) {
    return operators["ld"].apply(this, arguments);
  } else {
    return operators["eq"].apply(this, arguments);
  }
};

為什麼需要預設運算子?其實只是一個快捷方式。大多數時候我們要的都是 eq,如果每處都寫上運算子,程式碼會變得冗長又難看。對比看看:

Dispatcher.capture({
  "status": 200,
  "command": "message"
}, function (json) { /* display message */ });

Dispatcher.capture({
  "status$eq": 200,
  "command$eq": "message"
}, function (json) { /* display message */ });

顯然第一種更直觀。因此當運算子字串為 "" 時,就透過預設運算子來選擇實際的運算子。

把 Pattern 接上 Filter

var createFilter = function (condition) {
  return function (json) {
    if (arguments.length > 0) {
      return operators[""](condition, json);
    } else {
      return operators[""](condition);
    }
  };
};

之所以要考慮 json 沒傳入的情況,是為了應付某些細節,下一篇文章再說明。

撰寫運算子最需要的就是嚴謹性。因為 Dispatcher 是封裝好的元件,運算子一點點的不嚴謹,都會把缺陷埋得很深、很難找出。所以下一篇要討論單元測試,透過測試大幅提高 Dispatcher 的健壯性。

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