jquery - How to make a wrapper function in javascript? -


I have a very low click handler:

  $ (document) .on (' Click ',' .xxxbtn ', function (e) {....})   

I want to save one of the cookies in some of them.
I can write down like this:

  function default handler (e, callback) {callback (e); DoSomeJobs (); } $ (Document) .on ('click', '.xxxbtn', defaultHandler (e, function (e) {`different code in each BTN .... ....})   

But I think it should be handled well ( just look better and clear ):

  $ (document) .on ( 'Click', ' 

update
m Maybe my example is a bit unclear. I mean if i can create defaultHandler as function statement in javascript? Just function << Text "itemprop =" text ">

short answser : No, there is no way to say defaultHandler (e) {...}
<

Long answer :

It is possible to achieve something like this: order functions, functions which return the function ns. Yes In JS, such a thing is possible, and even clean, short codes are required to be written.

First of all, start with a simple example. You want to share the same handler for everything

  var logArgs = function (e) {console.log (arguments); } $ (Document) .on ('click', '.btn', logArgs);   

You can use that function as often as an event handler. It will always work but assume that you need some more specific logic. You may want to always identify the output before a certain string.

  var nameLogger = function (name) {return function (e) {console.log (name, arguments); }}; $ (Document) .on ('click', '.btn', named logger ('first button')); $ (Document) .on ('click', '.btn2', named logger ('second button')); As you can see, we call the function  named logger  with a name, which it remembers. Then it returns a new function, which is then used as an event handler, if applicable, your logger callback will be accessed through the scope of closing down to  name  and arguments Log in before.  

You can become crazy with such patterns, and it is really encouraged. To make this more relevant for {var setCookie}:

  var cookieSetter = function (eventHandler): The best way to write reusable event handler code in JS is by  

= Function (key, value) {document.cookie = key + '=' + + value + ';'; }; Return function (e) {set cookie ('whatever', eg something); Eventhandler (e); }; }; $ (Document) .on ('click', '.btn', cookieetter (function (e) {console.log ('Event Trigger', e);});

Comments

Popular posts from this blog

Pass DB Connection parameters to a Kettle a.k.a PDI table Input step dynamically from Excel -

multithreading - PhantomJS-Node in a for Loop -

c++ - MATLAB .m file to .mex file using Matlab Compiler -