Reputation: 4862
i use the JQuery load
function to append
(instead of replace) some html data to an element. My problem is the data is the this
scope on the load function. Can not use () =>
. How can i access a variable outside of the load callback ?
var element: JQuery;
$("<div></div>").load("http://www.google.de", function {
$(element).append(this);
});
Upvotes: 1
Views: 3746
Reputation: 250972
In TypeScript, when you use the () =>
syntax, it actually just creates a variable to contain the "current meaning of this" and then substitutes usages of this
to call the generated variable. You can do this manually in situations where you want both meanings of this
.
Here are some examples...
Normal use of this
in a callback. this
is the event target.
$('div').click( function () {
// this is the clicked element
alert('this: ' + this.id);
});
TypeScript arrow function used for a callback. this
is the lexical scope.
$('div').click( () => {
// this is the lexical scope
// i.e. the containing class, containing function, or window
alert('this: ' + this.id);
});
Manual example, creating a variable named self
to contain the lexical scope and leaving this
to be the event target.
var self = this;
$('div').click( function () {
// this is the clicked element
alert('this: ' + this.id);
// self is the lexical scope
// i.e. the containing class, containing function, or window
alert('self: ' + self.id);
});
It is worth bearing in mind that JavaScript walks the scope chain at runtime, so if a variable isn't defined inside of a function, JavaScript inspects the enclosing function for the variable. It keeps walking up the chain until it has checked the global scope.
This example shows this in action, but the nesting can be much deeper and it still works (i.e. a function inside of innerFunction
can still scope-walk to get to the test
variable.
var example = function () {
var test = 'A test';
var innerFunction = function () {
alert(test); // 'A test'
}
innerFunction();
}
example();
Upvotes: 6
Reputation: 275987
Just as you would expect. Any variable outside the function is available to you:
var element: JQuery;
var someOther = "123";
$("<div></div>").load("http://www.google.de", function(){
$(element).append(this);
$(this).text(someOther);
});
Upvotes: 1