1. 程式人生 > 其它 >JavaScript設計模式—— 釋出訂閱模式

JavaScript設計模式—— 釋出訂閱模式

ES5

var Event = {
    ClientListen : [],
    listen : function(key,fn) {
        if(!this.ClientListen[key]) {
            this.ClientListen[key] = []
        }
        this.ClientListen[key].push(fn)
    },
    trigger : function() {
        var key = Array.prototype.shift.call(arguments),
            fns 
= this.ClientListen[key] for(var i=0; i<fns.length; i++) { fns[i].apply(this, arguments) } } } function installEvent(target, source) { for(var i in source) { target[i] = source[i] } return target } var Obj = installEvent(Obj,Event) Obj.listen(
"sq888",function(price, sq) { console.log(price, sq) }) Obj.listen("sq888",function(price, sq) { console.log(price, sq) }) Obj.listen("sq998",function(price, sq) { console.log(price, sq) }) Obj.listen("sq998",function(price, sq) { console.log(price, sq) }) Obj.trigger("sq888",1000,'88')

ES6

class Event {
    constructor(){
        this.ClientListen = []
    }
    listen(key,fn) {
        if(!this.ClientListen[key]) {
            this.ClientListen[key] = []
        }
        this.ClientListen[key].push(fn)
    }
    trigger() {
        var key = Array.prototype.shift.call(arguments),
            fns = this.ClientListen[key]
        for(var i=0; i<fns.length; i++) {
            fns[i].apply(this, arguments)
        }
    }
}

class Obj extends Event {
    constructor(){
        super()
    }
}

var obj = new Obj()

obj.listen("sq888",function(price, sq) {
    console.log(price, sq)
})
obj.listen("sq888",function(price, sq) {
    console.log(price, sq)
})
obj.listen("sq998",function(price, sq) {
    console.log(price, sq)
})
obj.listen("sq998",function(price, sq) {
    console.log(price, sq)
})

obj.trigger("sq888",1000,'88')