观察者模式2

by 苹果熊

HTML

<div id="app">点我</div>
<div id="cont">内容</div>

JavaScript

var pub = {
	subs: {
  	any: []
  },
  on(type = 'any', fn, context) {
    fn = typeof fn === 'function' ? fn : context[fn]
    if(!this.subs[type]) {
    	this.subs[type] = []
    }
    this.subs[type].push({fn: fn, context: context || this})
  },
  off(type = 'any', fn, context) {
    var subs = this.subs[type]
    for(var i = 0; i < subs.length; i++) {
    	if(subs[i].fn === fn && subs[i].context === context) {
      	subs.splice(i, 1)
      }
    }
  },
  trigger(type = 'any', argv) {
		var subs = this.subs[type]
    for(var i = 0; i < subs.length; i++) {
    	subs[i].fn.call(subs[i].context, argv)
    }
  }
}
function makePub(o) {
	for(var i in pub) {
  	if(pub.hasOwnProperty(i) && typeof pub[i] === 'function') {
    	o[i] = pub[i]
    }
  }
  o.subs = {
  	any: []
  }
}

var app = document.getElementById('app')
var cont = document.getElementById('cont')
makePub(cont)
cont.on('work', function(s) {
	console.log('do work1')
  console.log(s)
})
app.onclick = function() {
	cont.trigger('work', 'my')
}
console.log(cont.subs)