請叫我重構控

基於個人興趣,最近(其實,就是今天... XD)在重構 Cleopatra (Mozilla Profiling GUI) 的時候碰到一個小問題:

window.postMessage 有辦法在接收端有辦法用 handleEvent 的介面來改寫嗎?
畢竟接收也是透過 window.addEventListener 來收訊息。

修改前
window.addEventListener("message", function messageFromAddon(msg) {
  // This is triggered by the profiler add-on.

  var o = JSON.parse(msg.data);
  switch (o.task) {
    case "importFromAddonStart":
      var totalReporter = enterProgressUI();
      gImportFromAddonSubreporters = totalReporter.addSubreporters({
        import: 10000,
        parsing: 1000
      });
      gImportFromAddonSubreporters.import.begin("Symbolicating...");
      break;
    case "importFromAddonProgress":
      gImportFromAddonSubreporters.import.setProgress(o.progress);
      if (o.action != null) {
          gImportFromAddonSubreporters.import.setAction(o.action);
      }
      break;
    case "importFromAddonFinish":
      importFromAddonFinish(o.rawProfile);
      break;
  }
});
修改後
var App = {
  init: function app_init() {
    window.addEventListener('message', this);
    window.addEventListener('click', this);
  },
  
  handleEvent: function app_handleEvent(evt) {
    switch (evt.type) {
        case 'message':
        this._handleMessage(evt.data);
        break;
      case 'click':
        break;
    }
  },
  
  _handleMessage: function app__handleMessage(data) {
    var o = JSON.parse(data);
    switch (o.task) {
      case "importFromAddonStart":
        var totalReporter = enterProgressUI();
        gImportFromAddonSubreporters = totalReporter.addSubreporters({
          import: 10000,
          parsing: 1000
        });
        gImportFromAddonSubreporters.import.begin("Symbolicating...");
        break;
      case "importFromAddonProgress":
        gImportFromAddonSubreporters.import.setProgress(o.progress);
        if (o.action != null) {
            gImportFromAddonSubreporters.import.setAction(o.action);
        }
        break;
      case "importFromAddonFinish":
        importFromAddonFinish(o.rawProfile);
        break;
    }
  }
};
App.init();

Make a guess?

答案是可以

因為 MessageEvent 是繼承自 Event
證明在此:http://jsfiddle.net/alivedise/Nqm6S/

Comments

comments powered by Disqus