`
zccst
  • 浏览: 3294869 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

PubSubJS的使用

阅读更多
作者:zccst

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







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

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

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


github地址:
https://github.com/mroderick/PubSubJS

如果在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');
}




如果您觉得本文的内容对您的学习有所帮助,您可以微信:
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics