Skip to content

Instantly share code, notes, and snippets.

@RudolfHattenkofer
Last active January 3, 2016 02:59
Show Gist options
  • Save RudolfHattenkofer/8399515 to your computer and use it in GitHub Desktop.
Save RudolfHattenkofer/8399515 to your computer and use it in GitHub Desktop.
// Register our actions here
actions_setup = function( $el, query_children ) {
// Initialize our apply_to_selector function
var apply = apply_to_selector( $el, query_children );
// The action to insert the links
apply( '.links-insert', function( $node ) {
// Add the event, don't forget to use jQuery.offon
// to avoid duplicate events!
$node.offon( 'click.links-insert', function() {
$('.button-container').append(
'<button class="button-click-me">Click me!</button>'
);
} )
} );
// The inserted button action
apply( '.button-click-me', function( $node ) {
$node.offon( 'click.button-click-me', function() {
alert( 'It worked!' );
} );
} );
}
// Applies a function to a specific query
apply_to_selector = function( $el, query_children ) {
// Wrapper for easier calling
return function( selector, func ) {
// Apply to self (if we match the selector)
if( $el.is( selector ) )
func( $el );
// Apply to all of our matching children
if( query_children ) {
$el.find( selector).each( function() {
func( $(this) );
} );
}
}
}
// This handles all changes to the DOM:
handle_dom_change = function( summary, query_children ) {
// Avoid certain situations where there are no events
if( ! summary[0] || ! summary[0].added )
return;
var added = summary[0].added;
for( var i = 0; i < added.length; i++ ) {
var $el = $( added[ i ] );
actions_setup( $el, query_children );
}
}
/**
* Note that this is NOT within a
* $(document).ready(), this way the whole
* document is treated as new elements already
* and all our events get applied automagically.
* If you wrap this, make sure to call:
*
* actions_setup( document, true );
*
* manually.
*/
new MutationSummary({
callback: handle_dom_change,
queries: [{
all: true
}]
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment