triggering a bind "function" via string versus calling a function

I am working on someone else's code and came across something puzzling.

Rather than calling functions the code is calling binding functions and then triggering it through a string.

Example 1:

bind("hello.world", function(){
     console.log("hello world");
});

trigger("hello.world");

Rather than ---

Example 2:

helloWorld = function(){
    console.log("hello world");
}

helloWorld();

What are the pros and cons between Example 1 and Example 2. Thank you.


Well, since javascript is an event driven programming language, I would recommend the first one.
Here's a case that illustrates the advantages of using event-handlers instead of simple function calls :

function someEventHandler(){
    if($(this).hasClass('some-class'))
        // do something
}
$('element').bind('eventName.eventNamespace',someEventHandler);

Now, if you simply call this function such as :

someEventHandler();

you can see that it will have no effect, because it is designed to be executed in a dom element context.
If you trigger the event that has the someEventHandler function as it's event-handler :

$('element').trigger('eventName.eventNamespace');

the function is called in the element context, something like :

someEventHandler.call($('element').get(0));

which will have the desired effect.
Moreover, you can bind multiple event-handlers to the same event and bind it to multiple elements.
If you would like to call a function for each of a list of dom elements, you would have to do something like this :

someEventHandler.call($('element1').get(0));
someEventHandler.call($('element2').get(0));
someEventHandler.call($('element3').get(0));
// ... and so on

while, with the first method would much more easier :

$('element1,element2,element3').bind('eventName.eventNamespace',someEventHandler);
$('element1,element2,element3').trigger('eventName.eventNamespace');

Note that the approach you take depends on the context you're using these functions. If your function has nothing to do with a dom element or you do not want more objects to subscribe to your event, you probably should keep it simple and use classic function declarations and calls.

链接地址: http://www.djcxy.com/p/356.html

上一篇: 在其他功能完成后收听功能

下一篇: 通过字符串触发绑定“功能”与调用函数