Reputation: 18301
For Instance, lets say we want to check if this
has any events under the namespace proxy; I currently do:
// 'this' is not a DOM element
if ($($(this).data('events')).length === 0 || $($(this).data('events').proxy).length === 0) {
// Do something If there are no events
}
This is how I do it now in order to assure that the .data('events')
object has been created (if there has not been a .bind called prior to reading .data('events')
it will be undefined) AND it has an event under the proxy
namespace.
Is there a better way to do this without throwing an error? It'd be great if I could do something like:
if($(this).data('events').proxy.length === 0) {
// Do something if there are no proxy events
}
However, if there has not been anything bound to this
the code snippet will throw an error because .data('events')
will be undefined and therefore will not have a .proxy
accessor.
Upvotes: 3
Views: 1090
Reputation: 359816
Just beef up the truthiness checks accordingly:
var data_events = $(this).data('events');
if(!data_events || data_events.proxy.length === 0) {
// Do something if there are no proxy events
}
Upvotes: 1