Created
August 26, 2010 14:21
-
-
Save chrisjpowers/551472 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This function returns a new function that will run | |
// the given function in the context of the given scope | |
// ie 'this' will be whatever you pass in as 'scope' | |
function scoped(fn, scope) { | |
return function () { | |
return fn.apply(scope, arguments); | |
} | |
} | |
var Obj = { | |
test: 'success', | |
a: function() { | |
console.log(this.test); | |
} | |
}; | |
// This works as expected -- the 'a' function is run with | |
// 'this' being Obj by default. | |
Obj.a(); //=> 'success' | |
// We can use the Obj.a function as a callback function | |
// for this jQuery click event. It seems like it should work fine... | |
$('#el').click(Obj.a); | |
// ...but it doesn't. jQuery runs event callback functions in | |
// a scope where 'this' is the clicked element. Usually this is | |
// helpful, but in cases like this, we will get an error. | |
$('#el').click(); //=> Error -- $('#el') doesn't have a 'test' property | |
// To fix this problem, we need to use the scoped function to | |
// explicitly run the Obj.a function in the context of Obj. | |
// Now 'this' will be Obj rather than the clicked element. | |
$('#el').click(scoped(Obj.a, Obj)); | |
$('#el').click(); //=> 'success' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment