【发布时间】: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