jQuery plugin to dynamically register events on dynamically added items ondemand

 

(function ($) {
$.fn.EventHandler = function (options) {
var defaults = $.extend({}, options), $element, $eventsArray = [], $activityArray = [];
$element = $(this);
if (options.onEvent.length != 0) {
if(options.startEvent){
$element.on(options.startEvent, function(){
$eventsArray = options.onEvent;
$eventsArray.forEach(function (oneEvent) {
$(options.listen).on(oneEvent.event, function () {
$activityArray = oneEvent.activity;
$activityArray.forEach(function (activityArrayItem) {
$(options.target)[activityArrayItem.action](activityArrayItem.actionValue)
});
});
});
});
}
}
}
}(jQuery))
//AND USE IT LIKE THIS
$('.gqtrigger1').EventHandler({
startEvent: 'click',
listen: '#gq1',
target: '#col1',
onEvent: [
{
event: 'shown.bs.collapse',
activity: [
{
action: 'removeClass',
actionValue: 'fa-plus'
},
{
action: 'addClass',
actionValue: 'fa-minus'
}
]
},
{
event: 'hidden.bs.collapse',
activity: [
{
action: 'removeClass',
actionValue: 'fa-minus'
},
{
action: 'addClass',
actionValue: 'fa-plus'
}
]
}
]
});