該模式大多數用於自定義事件app
var event = {} event.cacheList = {} event.on = function (key, fn) { if (!event.cacheList[key]) { event.cacheList[key] = [] } event.cacheList[key].push(fn) } event.fire = function () { var key = Array.prototype.shift.apply(arguments) var fns = event.cacheList[key] if (!fns || fns.length === 0) { return false } for (var i = 0, len = fns.length; i < len; i++) { fns[i].apply(this, arguments) } } event.remove = function (key, fn) { var fns = event.cacheList[key] if (!fns || fns.length === 0) { return false } if (!fn) { fns && (fns.length = 0) } else { for (var i = 0, len = fns.length; i < len; i++) { if (fns[i] === fn) { fns.splice(i, 1) } } } } var installEvent = function (obj) { for (var key in event) { obj[key] = event[key] } } var sellOffice = {} installEvent(sellOffice) sellOffice.on('square200', function () { console.log('square200') }) sellOffice.on('square200', function () { console.log("square200 2") }) sellOffice.fire('square200') sellOffice.remove('square200') sellOffice.fire('square200')
這裏其中關鍵的一點就是利用對象鍵值對存儲了事件,在某個事件調用存儲的事件,移除事件也是經過對對象從新賦值。這裏使用對象做爲存儲的數據格式是由於經過鍵查詢的複雜度是1,能夠快速搜索到某個鍵存儲的函數列表。函數