Created
April 1, 2016 07:24
-
-
Save hjzheng/b4beb9e02bedeef8a28b4902b94bbd05 to your computer and use it in GitHub Desktop.
订阅和发布 时间总线机制
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var OB = function(){ | |
this.subscribers = []; | |
} | |
OB.prototype = { | |
constructor: OB, | |
//订阅方法,返回订阅event标识符 | |
sub:function(evt, fn){ | |
this.subscribers[evt] ? this.subscribers[evt].push(fn) : | |
(this.subscribers[evt] = []) && this.subscribers[evt].push(fn); | |
return '{"evt":"' + evt +'","fn":"' + (this.subscribers[evt].length - 1) + '"}'; | |
}, | |
//发布方法,成功后返回自身 | |
pub:function(evt , args){ | |
if(this.subscribers[evt]){ | |
for (var i in this.subscribers[evt]) { | |
if(typeof(this.subscribers[evt][i]) === 'function'){ | |
this.subscribers[evt][i](args); | |
} | |
}; | |
return this; | |
} | |
return false; | |
}, | |
//解除订阅,需传入订阅event标识符 | |
unsub:function(subId){ | |
try{ | |
var id = JSON.parse(subId); | |
this.subscribers[id.evt][id.fn] = null; | |
delete this.subscribers[id.evt][id.fn]; | |
}catch(err){ | |
console.log(err); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment