Thursday, May 21, 2015

jQuery event namespacing

jsfiddle

var obj = $({});

function log(evt, obj, src) {
    $('#log').append(obj + ':' + evt.type + '.' + evt.namespace + ' ' + src + '\n');
}

obj.on('save.billing', function (evt, obj) {
    log(evt, obj, 'save base');
});

obj.on('save.billing.widget', function (evt, obj) {
    log(evt, obj, 'save widget');
});

obj.on('save.billing.consumer', function (evt, obj) {
    log(evt, obj, 'save consumer');
});

//triggers base, widget, and consumer
obj.trigger('save.billing', 1);
//remove widget listeners
obj.off('.billing.widget');
//triggers base and consumer
obj.trigger('save.billing', 2);
//remove all billing listeners
obj.off('.billing');
//triggers nobody
obj.trigger('save.billing', 3);