简体   繁体   中英

Functional jQuery: Custom Events or Functions?

Being new to functional programming, I was working on my application's javascript (using jQuery exclusively), and wondering how jQuery's event system relates to it's functional programming paradigm.

I have a function setupAccountHeader that could easily be either a document-bound event like

$(document).bind('setupAccountHeader', function() {
    blah, blah, blah;
});

OR

var setupAccountHeader = function() {
    blah, blah, blah;
};

Then, either triggered or called when needed.

So I have two questions:

1) Which style is preferred for functional jQuery or is this purely a matter of taste/personal-style? What about implications for big-picture architecture?

2) Are there any good resources for functionally-styled jQuery? I feel like this is John Resig's intent, but I can't find much in the way of info or guides on what this means in implementation.

The nice thing about the second style is that it will show in the debugger call stack with its name, as opposed to "anonymous", which I find a bit more helpful.

You could achieve the above along with jQuery's added event mechanisms (as Elzo said) with the following:

$(document).bind('setupAccountHeader', setupAccountHeader);
  • The official method of binding an event in jQuery is the first version, this way you have similar methods for binding and unbinding events. I think is not that much of a personal preference as it helps code readability, getting support for your code and using other functions related and included in jQuery like preventing default event bubbling. The second example of the first question is correct from JavaScript, but this style is not used anywhere in jQuery documentation.

Update

If you to bind events and use the benefits of a normalized event system you'll use the first version for regular (blur, focus, load, resize, scroll, unload, beforeunload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error) or your custom events.

They are actually not similar. In order to be similar in the second one you'll have to attach to document some events. Try to cancel them to get the idea.

// first version
$(document).unbind('setupAccountHeader'); // will cancel the binding of some action
// second version
setupAccountHeader = null; // will just cancel a variable 

The other version is just a closure that you can use everywhere in JavaScript, and is used in this case as well. It doesn't have any specific meaning without a context.

  • I don't really understand the second question. Maybe you can detail what you mean. I'm not a native English speaker.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM