Vikash Balasubramanian
Vikash Balasubramanian

Reputation: 3233

dynamic adding of event targets javascript

i have a code snippet like this.

$(document).on("click", event_target, some_function);

DEFAULT BEHAVIOUR:

If i pass event_target as null or empty string, all clicks on the document are handled.

DESIRED BEHAVIOUR

I want that if event_target is an empty string the event shouldn't be handled.

CURRENT APPROACH

Now i just add a if statement in the handler and if target is document i simply do nothing.

Is there a better approach to avoid unnecessarily calling the handler for all clicks?

Upvotes: 4

Views: 74

Answers (1)

vbm
vbm

Reputation: 112

Why don't you just do what you're currently doing inside an if block? Set up the click handler only if event_target is not an empty string.

if (event_target !== '')
    $(document).on("click", event_target, some_function);

Upvotes: 2

Related Questions