每週優秀代碼賞析系列【二】----Jif

一.簡介 Jif是一個輕量級的events,Jif提供了事件監聽on、發送send和清空clear接口,咱們能夠爲其擴展remove 等接口。
Jif也是觀察者模式的一種優雅實現。javascript

 
二.代碼公佈 下面就公佈本週的優秀代碼:php

var Jif = function () {
            this._listeners = {};
        };

        Jif.prototype = (function (undefined) {
            return {
                on: function (event, callback) {
                    if (this._listeners[event] === undefined) {
                        this._listeners[event] = [];
                    }

                    this._listeners[event].push(callback);
                },

                clear: function (event, callback) {
                    var listeners = this._listeners[event];
                    var i = listeners.length;

                    if (listeners === undefined) {
                        throw new Error('Unknown event type: ' + event);
                    }

                    if (callback === undefined) {
                        this._listeners[event] = [];
                        return;
                    }

                    while (i > 0) {
                        i -= 1;
                        if (listeners[i] === callback) {
                            this._listeners[event].splice(i, 1);
                        }
                    }
                },
         
                send: function (event, msg) {
                    var listeners = this._listeners[event];
                    var i = listeners.length;

                    if (listeners === undefined) {
                        throw new Error('Unknown event type: ' + event);
                    }

                    while (i > 0) {
                        i -= 1;
                        listeners[i](msg);
                    }
                }
            };
        })();

 
 
三.用法html

var events = new Jif();
        //訂閱天氣
        events.on('weather', function (weather) {
            alert('today is   ' + weather.condition);
        });
        //發佈天氣
        events.send('weather', { condition: 'sunny' });

能夠看得出來,這裏實現了發佈與訂閱,可是忽略了發佈者和訂閱者的概念,而是統一由events中轉。
 
 
四.其餘相關連接 Observer Design Pattern Using JavaScript:http://www.codeproject.com/KB...
javascript觀察者模式: http://www.cnblogs.com/rubylo...
Javascript亂彈設計模式系列(1) - 觀察者模式(Observer):http://www.cnblogs.com/liping...
轉載於猿2048:⇛《每週優秀代碼賞析系列【二】----Jif》java

相關文章
相關標籤/搜索