【问题标题】:Passing arrays via jQuery tiny PubSub通过 jQuery tiny PubSub 传递数组
【发布时间】:2012-08-28 02:09:23
【问题描述】:

jQuery tiny PubSub 在传递原始值或对象时非常有用,但在处理数组时会遇到一些问题。所以我必须将数组包装成一个对象。

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

我见过它的一些改进版本,主要侧重于缓存订阅者,但它们都不能传递数组。所以,两个问题:

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

【问题讨论】:

  • 为什么不JSON.stringify他们?
  • @JosephSilber 因为var o={};JSON.parse(JSON.stringify(o))===o //false,我无法通过这种方式通过 PubSub 传递 dom。

标签: javascript jquery publish-subscribe


【解决方案1】:

您不能对数组使用 apply 函数。您只能使用应用和调用对象实例。

数组的每个索引都可以包含对象。

【讨论】:

  • 事实上,是的,我可以。 function trigger(event,data){console.log(event,data)}function publish(){trigger.apply({}, arguments)}publish('test',[2,3,4]);//'test',[2,3,4]。唯一不同的是jQuery的.trigger(),好像对数组有某种特殊的转换;
【解决方案2】:

好吧,反正我想通了。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 2013-07-30
    • 1970-01-01
    相关资源
    最近更新 更多