<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> // 订阅发布者模式简单版 function test(){ var obj = {} var on = function(name,callback){ if(!obj[name]){ obj[name] = [] } obj[name].push(callback) } var emit = function(name){ if(!obj[name]) return; var length = obj[name].length, i = 0, temp = Array.prototype.slice.call(arguments,1) for(;i<length;i++){ obj[name][i].apply(this,temp) } } return { on, emit } } var a = test() a.on(‘a‘,function(a){ console.log(a) }) a.on(‘a‘,function(a){ console.log(a) console.log(1) }) a.emit(‘a‘,3) // 高级计数器 var demo = function(l){ var obj = {} var on = function(name,callback){ if(!obj[name]){ obj[name] = { callback:callback, length:l, result:{} } } } var dispatch = function(name,result){ if(!obj[name]) return; var length = --obj[name].length; for(var k in result){ obj[name].result[k] = result[k] } if(!length){ obj[name].callback(obj[name].result) delete obj[name] } } return { on, dispatch } } var b = demo(2); b.on(‘test‘,function(result){ console.log(result) }) b.dispatch(‘test‘,{a:{a:‘sfdsf‘}}) b.dispatch(‘test‘,{b:321}) </script> </body> </html>
时间: 2024-10-09 01:19:49