原文出自PTT Web_design版:
http://www.ptt.cc/bbs/Web_Design/M.1377320015.A.5E6.html

原po想要整理如下的code:

window.onload = function() {
   bind('.delete_button_1').(function() {});
   bind('.delete_button_2').(function() {});
   ...etc

   bind('.add_button_1').(function() {});
   bind('.add_button_2').(function() {});
   ...etc
}

其實這問題對於支援handleEvent以及addEventListener的瀏覽器來說並非難事,

var App = {
    init: function app_init() {
    this.getAllElements();
    
    this.addButton1.addEventListener('click', this);
    this.addButton2.addEventListener('click', this);
    this.deleteButton1.addEventListener('click', this);
    this.deleteButton2.addEventListener('click', this);
  },
  getAllElements: function app_getAllElements() {
    // Fetch elements to this object here.

  },
  handleEvent: function app_handleEvent(evt) {
    // According to evt.target do something here.

  }
};
window.onload = function() {
    App.init();
};

不意外的IE9之後才有機會支援「把內含handleEvent函數的物件當成EventListener」。

一般MVC framework應該都有解決這個問題的方法,
之前在trace CanJS的時候看到它的作法如下:

var App = {
  init: function app_init() {
    this.bindEvents();
  },

  bindEvents: function app_bindEvents() {
    for (var prop in this) {
      var a = prop.split(' ');
      if (a.length > 1) {
        // Pseudo code: Delegate element a[0] with a[1] event
        $(a[0]).on(a[1], this[prop].bind(this));
      }
    }
  },

  '.delete_button_1 click': function on_delete_button_1_click() {
    // do sth...
  },

  '.delete_button_2 click': function on_delete_button_2_click() {
    // do sth...
  },

  '.delete_button_3 click': function on_delete_button_3_click() {
    // do sth...
  },

  'form submit': function on_form_submit() {
    // do sth...
  }
};

簡言之用約定俗成的方式將"selector event"當成key, callback當成value,
寫在object裡面然後在初始階段去過濾有這樣的property的話就自動做delegate的動作。

Comments

comments powered by Disqus