I’d like to use a variable to store which event i’m going to bind to.
Something like:
var the_event = 'mouseover';
$().bind(the_event, function(){
console.log('hi there!');
});
I could achieve the same thing with ifs, but i’d rather use a better way, might one exist!
What i want to do, with ifs:
var the_event = 'mouseover';
var the_function = function(){
console.log('hi there!');
}
if(the_event == 'mouseover'){
$().bind('mouseover', the_function);
} else if(the_event == 'click'){
$().bind('click', the_function);
}
Thank you!
EDIT:
What i’m actually tring to do is:
var events = {
one: 'mouseover',
two: 'mouseout'
};
$().bind({
events.one: function(){
console.log('1');
},
events.two: function(){
console.log('2');
},
);
Your first example would work fine if there were something in the
$()at the beginning.bindaccepts a string, it doesn’t care whether the string comes from a literal or from a variable.This:
is exactly the same as this:
…other than the existence of the
event_namevariable, of course. Gratuitous live exampleIf you want to do multiple events, you can do that too, but you have to create the object you’re passing to
bindin advance:Live example
You can’t do it directly in the literal because the thing to the left of the
:in an object literal must be a literal or a literal string, it cannot be the result of an expression (and so cannot be a variable reference), e.g., this will not work:So applying that to the code example you just added to the question, you’d get: