发布订阅机制
2015-08-03 17:39
246 查看
发布/订阅实例
1、发布var pubsub = {}; (function(q) { var topics = {}, subUid = -1; // Publish or broadcast events of interest // with a specific topic name and arguments // such as the data to pass along q.publish = function( topic, args ) { if ( !topics[topic] ) { return false; } var subscribers = topics[topic], len = subscribers ? subscribers.length : 0; while (len--) { subscribers[len].func( topic, args ); } return this; };
2、订阅
// Subscribe to events of interest // with a specific topic name and a // callback function, to be executed // when the topic/event is observed q.subscribe = function( topic, func ) { if (!topics[topic]) { topics[topic] = []; } var token = ( ++subUid ).toString(); topics[topic].push({ token: token, func: func }); return token; };
3、取消订阅
// Unsubscribe from a specific // topic, based on a tokenized reference // to the subscription q.unsubscribe = function( token ) { for ( var m in topics ) { if ( topics[m] ) { for ( var i = 0, j = topics[m].length; i < j; i++ ) { if ( topics[m][i].token === token) { topics[m].splice( i, 1 ); return token; } } } } return this; }; }( pubsub ));
相关文章推荐
- centos swig 编译c,python调用
- 还好活下来了
- “The run destination iOS Device is not valid for running the scheme”
- 一行字符中寻找英文单词个数
- url
- java发送邮件(1)
- 匹配邮箱正则表达式
- 指纹识别的基本原理
- zoj 3612 ——Median
- 合并百度影音的离线数据 with python 2.3 格式更新
- 指针操作一维数组
- JS 基础 用法
- Touch
- CSS中关于变量的基本教程
- 【十四】记录
- EF 连接mysql Authentication to host '' for user 'root' using method 'mysql_n(远程登录mysql失败)
- 图像处理概述
- Java面试宝典:42个面试题总结!
- ajaxSubmit与ajaxFileUpload的空值
- MySQL之查询性能优化三