每周优秀代码赏析系列【二】----Jif
2011-10-30 12:06 【当耐特】 阅读(3423) 评论(3) 编辑 收藏 举报一.简介
Jif是一个轻量级的events,Jif提供了事件监听on、发送send和清空clear接口,我们可以为其扩展remove 等接口。
Jif也是观察者模式的一种优雅实现。
二.代码公布
下面就公布本周的优秀代码:
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); } } }; })();
三.用法
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/scripting/Observer_Pattern_JS.aspx
javascript观察者模式: http://www.cnblogs.com/rubylouvre/archive/2010/03/29/1699203.html
Javascript乱弹设计模式系列(1) - 观察者模式(Observer):http://www.cnblogs.com/liping13599168/archive/2009/01/01/1366599.html