PubSubJS的使用

作者:zccst

2015-06-10
模块间通信的原理:
发布方,publish("key1");
订阅方,subscribe("key1", context, fn);多个订阅方形成订阅数组。
当发布方publish时,执行pubsub的方法,把所有订阅key为key1的方法全部执行一遍(数组)。


PubSubJS是用来解决模块间通讯的问题。

比如,在一个列表上部创建了一个新case时,需要在创建成功的时候刷新列表,将新创建的内容显示到列表中。这种情况其实也可以直接调用。

但是再比如,有很多其他模块需要订阅刷新列表,这时优势就显现出来。


github地址:
[url]https://github.com/mroderick/PubSubJS[/url]

如果在seajs

require('PubSub');
require('topic');

TOPIC是一个对象集合,字符串


订阅:

PubSub.subscribe(TOPIC.FEED.FEEDTEMPLATE.CREATE, $.proxy(function(){
this.queryTable();
}, this));
PubSub.subscribe(TOPIC.FEED.FEEDTEMPLATE.MODIFY, $.proxy(function(){
this.queryTable();
}, this));
PubSub.subscribe(TOPIC.FEED.FEEDTEMPLATE.DELETE, $.proxy(function(){
this.queryTable();
}, this));


发布:

ajax.post(DELETE_FEED_URL, {
args: {feedId:feedId},
success: jQuery.proxy(function(data, response, xhr){
//重点在这里
PubSub.publish(TOPIC.FEED.FEEDTEMPLATE.DELETE);
}, this),
fail: jQuery.proxy(function(msg, response, xhr){
alert(msg.length !== 0 ? msg.join('\r\n') : "系统繁忙,请稍后重试!");
}, this)
});


取消订阅:

destroy: function(){
this.undelegateEvents();
if(this.model){
this.model.unbind();
}
var $el = this.$el;
$el.unbind();
$el.empty();
//取消订阅
PubSub.unsubscribe(TOPIC.FEED.FEEDTEMPLATE.CREATE);
PubSub.unsubscribe(TOPIC.FEED.FEEDTEMPLATE.MODIFY);
PubSub.unsubscribe(TOPIC.FEED.FEEDTEMPLATE.DELETE);
}
feedListManage.prototype.destroy = function(){
this.view.destroy();
}

通过对外提供接口,在外部删除

需要在new之前先删除


//-----------------------------------外部文件----------------------------
//销毁主View

destroy: function() {
var currentView = this.currentView;
currentView && currentView.destroy && currentView.destroy();
},
feed: function(query){
//初始化feed管理页面,可传入query参数
//需要设置this.currentView
if(this.currentView && this.currentView instanceof FeedMain){
this.currentView.render(query);
} else {
this.destroy();
//初始化投放管理页面,可传入query参数
//需要设置this.currentView
this.currentView = new FeedMain($.extend(true, {}, {query: query}, this.options || {}))
}
this.renderLevel3Menu('feed');
}



如果您觉得本文的内容对您的学习有所帮助,您可以微信:
[img]http://dl2.iteye.com/upload/attachment/0109/0668/fb266dfa-95ca-3d09-b41e-5f04a19ba9a1.png[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值