Reputation: 19969
I have created this snippet http://jsfiddle.net/PexkV/
<script>
var arc={};
arc.handler={
background_color:'#8DBC8F',
console_this: function(str){
alert('lets write this to the console ' + str + ' ' + this.background_color);
}
}
$(document).ready(function(){
$('.more-click-me').on('click', arc.handler.console_this('here'));
$('.more-click-me').on('click', function(){
arc.handler.console_this('blue');
});
});
</script>
<div class='more-click-me'>lets write this</div>
and am unsure why the first event is being called automatically (the 'here' in the example). It seems like it should only be called in response to a click? What am I not getting? If I made some really stupid syntax issue, sorry in advance.
thx in advance
Upvotes: 0
Views: 59
Reputation: 1009
$('.more-click-me').on('click', arc.handler.console_this('here'));
$('.more-click-me').on('click', function(){
arc.handler.console_this('blue'); });
In the first line, you are calling the method & trying to bind the result to the event.
The second line is enough to set up the event binding.
Upvotes: 0
Reputation: 166001
Because you are calling the function and passing the return value of it to .on()
. The easiest way to achieve what you're trying to achieve will be to pass an anonymous function to .on()
, like you do in the 2nd example, and call your console_this
function within it:
$('.more-click-me').on('click', function () {
arc.handler.console_this('here');
});
Here's an updated fiddle.
Upvotes: 5
Reputation: 207521
because you are calling the function
arc.handler.console_this('here')
That is not assigning the function. It should look like the second one.
$('.more-click-me').on('click', arc.handler.console_this('here')); <-- wrong
$('.more-click-me').on('click', function(){ <-- right, uses a closure
arc.handler.console_this('blue');
});
so it should be
$('.more-click-me').on('click', function(){ arc.handler.console_this('here'); });
$('.more-click-me').on('click', function(){ arc.handler.console_this('blue'); });
Upvotes: 2