Passing arrays via jQuery tiny PubSub

会有一股神秘感。 提交于 2019-12-04 02:24:10

问题


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:

  • Is it a good idea to pass arrays via PubSub?
  • How to do that?

回答1:


You cannot use the apply function on arrays. You can only use apply and call to objects instances.

Arrays can contain objects in each one of its indexes.




回答2:


Alright, I figure it out anyway.

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]}


来源:https://stackoverflow.com/questions/12151913/passing-arrays-via-jquery-tiny-pubsub

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!