matthewatabet matthewatabet - 4 months ago 7
Javascript Question

How do I check for the existence of a backone callback?

Let's say I've installed a callback on my backbone model like so:

model.on('some_event', () => {
console.log('it happened.');
})


Is there a way to check that this callback is installed? My goal is to avoid installing the callback twice.

Answer

You can check to see if your model has an event registered with the following:

if(model._events && model._events['some_event']) {
    // already registered
}

Alternatively, if your goal is just to prevent registering a callback multiple times, you could precede your on call with an off call:

model.off('some_event').on('some_event', () => {
    console.log('it happened.');
});
Comments