Eventer.js - 一個微型事件發布/訂閱模塊

Eventer.js

自用的一個微型事件發布/訂閱模塊

特性

  • 支持鏈式操作
  • 支持批量訂閱事件
  • 啦啦啦,賣個萌

開始使用

首先引入本模塊:

<script src="http://path/to/eventer.js"></script>

我們給現有對象obj_margox綁定本模塊:

var obj_margox = {
    'name' : 'Margox',
    'age'  : 26,
    'sex'  : 'male',
    'isSingle'   : true,
    'girlFriend' : null
}

Eventer(obj_margox);

現在obj_margox這個對象已經具有了事件發布/訂閱的功能

訂閱事件

通過on方法可以訂閱單個或者多個事件

// 訂閱單個事件
obj_margox.on('grow', function() {
    this.age = this.age + 1;
    console.log(this.name + ' is ' + this.age + 'years old.');
});

// 訂閱多個事件
obj_margox.on({
    'hungry' : function() {
        console.log(this.name + ' is hungry!');
    },
    'tired' : function() {
        console.log(this.name + ' need a rest!');
    },
    'eat' : function(food) {
        console.log(this.name + ' just ate some ' + food);
    }
});

發布事件

通過trigger方法來發布(觸發)一個事件

obj_margox.trigger('grow'); // Margox is 27 years old.

obj_margox
    .trigger('hungry') // Margox is hungry!
    .trigger('tired') // Margox need a rest!
    .trigger('eat', 'breads'); // Margox just ate some breads

取消事件訂閱

通過off方法來取消訂閱指定的事件

obj_margox
    .off('hungry') // 取消訂閱hungry事件
    .trigger('hungry'); // nothing

項目地址: https://github.com/margox/Eventer.js

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!