通过jQuery tiny PubSub传递数组 [英] Passing arrays via jQuery tiny PubSub

查看:65
本文介绍了通过jQuery tiny PubSub传递数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery tiny PubSub 在传递原始值或对象时非常棒,但在使用数组时有些麻烦。所以我必须将数组包装到一个对象中。

jQuery tiny PubSub is great when passing primitive values or objects, but has some trouble with arrays. So I have to wrap arrays into an object.

(function($) {
  var o = $({});
  $.subscribe = function() {
    o.on.apply(o, arguments);
  };
  $.unsubscribe = function() {
    o.off.apply(o, arguments);
  };
  $.publish = function() {
    o.trigger.apply(o, arguments);
  };
}(jQuery));
$.subscribe('test',function(e,data){
    console.log(data);
})
$.publish('test',1);       //1
$.publish('test',{a:1});   //{a:1}
$.publish('test',[2,3,4]); //2
$.publish('test',{arr:[2,3,4]})  //{arr:[2,3,4]}

我见过它的一些改进版本,主要关注缓存订阅者,但没有一个可以传递数组。所以,有两个问题:

I've seen some improve versions of it, which mainly focus on caching subscribers, but none of them can pass arrays. So, two questions:


  • 通过PubSub传递数组是个好主意吗?

  • 如何要做到这一点?

推荐答案

好吧,我还是弄清楚了。

Alright, I figure it out anyway.

即使认为对其他人来说可能不是问题,但是无法通过 PubSub 传递数组对我来说非常困惑和不方便。所以我决定编写自己的 PubSub ,而不是使用jQuery的自定义事件。

Even thought it may not be a problem to others, but not being able to pass arrays via PubSub is very confusing and inconvenient to me. So I decide to write my own PubSub, instead of using jQuery's custom events.

(function (Global) {
    var cache = {};
    Global.PubSub = Global.PubSub || {
        on: function (e, fn) {
            if (!cache[e]) {
                cache[e] = [];
            }
            cache[e].push(fn);
        },
        off: function (e, fn) {
            if (!cache[e]) {
                return;
            }
            var fns = cache[e];
            if (!fn) {
                fns.length = 0;
            }
            var index = fns.indexOf(fn);
            if (index !== 0) {
                fns.splice(index, 1);
            }
        },
        trigger: function (e, data) {
            if (!cache[e]) {
                return;
            }
            var fns = cache[e];
            for (var i = 0; i < fns.length; ++i) {
                fns[i](e, data);
            }
        }
    };
})(typeof window !== 'undefined' ? window : this);
PubSub.on('test', function (e, data) {
    console.log(data);
});
PubSub.trigger('test', 1);
PubSub.trigger('test', {
    a: 1
}); //{a:1}
PubSub.trigger('test', [2, 3, 4]); //[2,3,4]
PubSub.trigger('test', {
    arr: [2, 3, 4]
}); //{arr:[2,3,4]}

这篇关于通过jQuery tiny PubSub传递数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆