Reputation: 2488
I would like to know if it's possible to store the events from a jQuery selector and apply it to another selector?
Something similar to $('selector').clone(true) but actually clones the events only and not the element.
$('.class1').on('click.click1', function(e) {
alert('click 1')
});
$('.class2').on('click.click2', function(e) {
alert('click 2')
});
// pseudo
$('.class2') cloneEvents from $('.class1');
Upvotes: 0
Views: 38
Reputation: 3392
Quick and dirty jQuery plugin for this purpose
This reads the event handlers bound to $source
via jQuery using the internal method _data
, iterates over them and binds them to $target
. Derived from this snippet.
;(function($, doc, win) {
"use strict";
$.fn.cloneEventsFrom = function($source) {
var $this = $(this),
source = $source.get(0);
$.each($._data(source, 'events'), function() {
$.each(this, function() {
$this.bind(this.type, this.handler);
});
});
};
})(jQuery, document, window);
Usage Demo here: http://jsfiddle.net/marionebl/4Jv37/1/
var $target = $('.target'),
$source = $('.source')
$target.cloneEventsFrom($source);
Upvotes: 1