javascript - Extending jQuery click handler (patching $.fn.click function?) to check for a condition -
javascript - Extending jQuery click handler (patching $.fn.click function?) to check for a condition -
update per comments
@adeneo: armed answers this question syntax disabled attribute , this question custom attributes, felt content adding attribute elements other ones listed in docs ones can "actually disabled". indeed of <a> , <span> elements may obtain attribute, more unified way address them css , js.
in effort concise , future-proof (e.g. adds input or 2 page later on), attach click event listeners similar elements @ 1 time - , handle them according element is. question prompted necessity disable elements until ajax request completes. phone call gets triggered click, , want prevent additional calls before first 1 completes.
@patrick q don't know how convey feasibility of intention short code snippet - wrote illustration in codepen:
example on codepen. original question:i add together status "click" event listeners check if target element disabled.
some of links have or obtain "disabled" attribute (for number of reasons using links more convenient - although interaction handled js). in case, click handler homecoming false (i.e. preventdefault , stoppropogation) right away, disabled link indeed disabled.
i of course of study search click handler attachments in code , add together status in each individually - that's really un-dry. way bind/unbind events based on attribute - seems way messy well... i'd alter in 1 place just works everywhere :-).
per jquery docs, click attaching listeners shorthand $.on(). imagine extend functionality of that... how?
is right direction think in?
you can monkey patch (replace) jquery $.on method add together logic, it's going pain maintain, since time jquery changes, you'll need update patch well.
as proof of concept, here's working monkey patch $.click - :
jquery.fn['click'] = function( data, fn ) { var wrap = function(handler) { homecoming function(e) { if ($(e.currenttarget).hasclass('disabled')) { e.stopimmediatepropagation(); homecoming false; } else { handler(e); } } } if(arguments.length > 0) { if(typeof fn == 'undefined') { this.on('click', null, wrap(data), fn ); } else { this.on('click', null, data, wrap(fn) ); } } else { this.trigger('click'); } }; note ended having reproduce logic original implementation handle variation in possible arguments correctly.
you write wrapper $.on , forcefulness team utilize it, inevitably forget it, , you'll end mysterious discrepancies drive people mad.
in end, want allow browser worry using form elements <button> deed correctly when disabled, , styling them necessary.
javascript jquery
Comments
Post a Comment