Javascript 试图理解此代码(发布/订阅库)
这是彼得·希金斯的酒吧分馆: 我不理解发布的逻辑和功能:Javascript 试图理解此代码(发布/订阅库),javascript,jquery,Javascript,Jquery,这是彼得·希金斯的酒吧分馆: 我不理解发布的逻辑和功能: cache[topic] && d.each(cache[topic], function () { **this.apply(d, args || []);** //what is happening here? }); 这部分的目的是什么?除了在此上下文中发布事件外,&&用作以下内容的简写: if (cache[topic]) { d.each(cache[topic], function() { …
cache[topic] && d.each(cache[topic], function () {
**this.apply(d, args || []);** //what is happening here?
});
这部分的目的是什么?除了在此上下文中发布事件外,
&&
用作以下内容的简写:
if (cache[topic]) {
d.each(cache[topic], function() { … });
}
这是因为&
(和|
)是,因此如果左侧的计算结果为假
-ish值(或真
-ish值,在|
的情况下),则不会对右侧进行计算
例如:
> function foo(result) { console.log("foo"); return result; }
> function bar(result) { console.log("bar"); return result; }
> foo(false) && bar(true);
foo
false
>函数foo(result){console.log(“foo”);返回结果;}
>函数栏(结果){console.log(“bar”);返回结果;}
>foo(假)和bar(真);
福
假的
在此上下文中,
&&
用作以下内容的简写:
if (cache[topic]) {
d.each(cache[topic], function() { … });
}
这是因为&
(和|
)是,因此如果左侧的计算结果为假
-ish值(或真
-ish值,在|
的情况下),则不会对右侧进行计算
例如:
> function foo(result) { console.log("foo"); return result; }
> function bar(result) { console.log("bar"); return result; }
> foo(false) && bar(true);
foo
false
>函数foo(result){console.log(“foo”);返回结果;}
>函数栏(结果){console.log(“bar”);返回结果;}
>foo(假)和bar(真);
福
假的
基本上,使用args(如果传递了任何参数)调用每个主题回调(如果有)。因此,您可以:
$.subscribe('do_something', function(str) { alert(str + ' world!')});
$.subscribe('do_something', function(str) { console.log(str)});
$.publish('do_something', ['Hello']); // will alert Hello world! and output 'Hello' to console
基本上,使用args(如果传递了任何参数)调用每个主题回调(如果有)。因此,您可以:
$.subscribe('do_something', function(str) { alert(str + ' world!')});
$.subscribe('do_something', function(str) { console.log(str)});
$.publish('do_something', ['Hello']); // will alert Hello world! and output 'Hello' to console
如果定义了cache[topic],则为d的每个元素应用函数,该函数使用d参数调用该元素的apply方法;如果未定义args,则为args或空数组
如果定义了cache[topic],则为d的每个元素应用函数,该函数使用d参数调用该元素的apply方法;如果未定义args,则为args或空数组