¿Existe una función de desvinculación "global" en jQuery, de modo que pueda eliminar todos los eventos vinculados de un espacio de nombres dado? p.ej:
// assume these are the events bound to different elements $('#foo').bind('click.myNS', ...); $('#bar').bind('keyup.myNS', ...); $('#baz').bind('dblclick.myNS', ...); // magic occurs here... $.magicalGlobalUnbindFunction('.myNS'); // ...and afterwards, the three binds from above are gone Todos los ejemplos que he visto para desvincular requieren que se seleccionen algunos elementos primero. Supongo que técnicamente podrías hacer $('*').unbind('.myNS') , pero eso parece muy ineficiente.
Puede agregar myNS como una clase a cada uno de los elementos en los que desea desvincular los eventos.
Debe usar los métodos On y Off de jQuery. Utilice el documento como selector.
$(document).off('.myNS'); $(document).on('click.myNS','#foo', ...); $(document).on('keyup.myNS','#bar', ...); $(document).on('dblclick.myNS','#baz',''');entonces sus métodos podrían verse como
$(document).on('click.myNS','#foo', fooClicked); var fooClicked = function(e){ var $this = $(e.target); // do stuff }Siempre puede envolver $.fn.bind y luego almacenar en caché las referencias necesarias:
(function ($) { var origBind = $.fn.bind, boundHash = {}; $.fn.bind = function (type, data, fn) { var namespace = '', events = []; if (typeof type === 'string') { // @todo check the allowed chars for event namespaces. namespace = type.replace(/^[^.]+/, ''); if (namespace.length) { events = boundHash[namespace]; // Namespaces can hold any number of events. events = boundHash[namespace] = $.isArray(events) ? events : []; // Only really need ref to the html element(s) events.push({ type: type, fn: $.isFunction(fn) ? fn : data, that: this.length > 1 ? this.toArray() : this[0] }); } } origBind.apply(this, arguments); }; // namespace to be muffled. Feel free to qualify a specific event type. $.muffle = function (namespace, type) { var events = []; if (boundHash.hasOwnProperty(namespace)) { events = boundHash[namespace]; $.map(events, function (event) { var _type = type || event.type; if (event.type.indexOf(_type) === 0) { $(event.that).unbind(_type, event.fn); } }); // @todo think of better return value. return true; } // @todo think of better return value. return false }; })(jQuery);