Skip to content

Instantly share code, notes, and snippets.

@jcinis
Created March 15, 2013 16:00
Show Gist options
  • Save jcinis/5170945 to your computer and use it in GitHub Desktop.
Save jcinis/5170945 to your computer and use it in GitHub Desktop.
jQuery plugin to add event triggering to dom elements anytime they append or are appended. The reason for creating this is was to allow backbone.js views to be aware of their being added to the dom and to trigger post-render functionality.
/**
* Adds event triggering whenever an append takes place.
*
* - Parent is given an "append" trigger with the child as an arguement
* - Child is given an "appended" trigger with the parent as an argument
*
* @author Jessey White-Cinis <jcinis@gmail.com>
*/
(function($) {
var jqueryAppend = $.fn.append;
$.fn.append = function () {
// trigger append event
var rtn = jqueryAppend.apply(this, arguments).trigger("append", arguments);
// trigger appended event
$(arguments).trigger("appended", this);
return rtn;
};
})(jQuery);
@jcinis
Copy link
Author

jcinis commented Mar 15, 2013

This works great for adding focus events to form elements since it focus can not be triggered until an input is rendered into the dom. Essentially this allows for postRender functionality to be added.

var MyView = Backbone.View.extend({

    events: {
        'appended':'whenAppended'
    },

    initialize: function(){},
    render: function(){},
    whenAppended: function(event,parent){
        console.log('I was just appended to', parent);
        this.$el.find('input').focus();
    }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment