Reputation: 779
I looked through other same title postings but I did not see explanation(or maybe they were not same question as far as I can see) that helped me see what's going on).
So basically, what I understand well is the implicit binding where if you use something.func, then 'this' is set to 'something'.
Now, I am sort of jumping into jquery and see something like below
$("button").click(user.clickHandler);
I thought user.clickHandler would make 'user' as this when clickHandler was invoked but chrome developer shows me that it's not(it's button is set to 'this'). And I understand I need to use bind to specify the 'user'. Why is this the case? I thought I understand implicit binding fine in javascript. I am just not sure how to read this..
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button>Get Random Person</button>
<input type="text">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.js"><\/script>')
</script>
<script>
var user = {
data : [
{name: "T.Woods", age:37},
{name:"P.Mickelson", age:43}
],
clickHandler:function(event){
var randomNum = ( (Math.random () * 2|0) +1) -1; // random
$("input").val(this.data[randomNum].name + " " + this.data[randomNum].age);
}
}
$("button").click(user.clickHandler);
</script>
</body>
</html>
Upvotes: 0
Views: 57
Reputation: 1
Try using jQuery.proxy( function, context [, additionalArguments ] )
$("button").click($.proxy(user.clickHandler, user));
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button>Get Random Person</button>
<input type="text">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
// window.jQuery || document.write('<script src="js/jquery.js"><\/script>')
</script>
<script>
var user = {
data: [{
name: "T.Woods",
age: 37
}, {
name: "P.Mickelson",
age: 43
}],
clickHandler: function(event) {
console.log(this, event);
var randomNum = ((Math.random() * 2 | 0) + 1) - 1; // random
$("input").val(this.data[randomNum].name + " " + this.data[randomNum].age);
}
}
$("button").click($.proxy(user.clickHandler, user));
</script>
</body>
</html>
Upvotes: 1
Reputation: 668
When jQuery dispatches events (see the jQuery.event.trigger
function in the jQuery code), it uses apply to bind the element receiving the event to this
.
I suggest you replace
$("button").click(user.clickHandler);
by
$("button").click(function(e) {user.clickHandler(e);});
Upvotes: 1