This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
Im currently trying to use a Promise to resolve fetching models from database. In the following was:
Promise.resolve(app.Departments.fetch()).then(function(response){
console.log(response);
this.$el.html( this.template( {depts: app.Departments.toJSON()} ));
this.$form = this.$('#form-employee');
this.$form.validator();
return this;
})
Consider everything is inside the render method and the method is inside a Backbone.View.extend({}) object. The problem is that inside the Promise.resolve() function the context of this is different from the context inside the View object which it throws an error not knowing what does this refers to. Is there anyway to pass to Promise.resolve the correct context of this?
Use a local reference for this:
var self=this;
Promise.resolve(app.Departments.fetch()).then(function(response){
console.log(response);
self.$el.html( self.template( {depts: app.Departments.toJSON()} ));
self.$form = this.$('#form-employee');
self.$form.validator();
return self;
})
Related
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
I'm trying to use the FourSquare API to return location information within my React App. To do this I'm using this useful package: https://www.npmjs.com/package/foursquarevenues
This package uses promises to make the API call. My code calls the package as following. The API call works great and I can log the response - however when I try to set the state it returns this.setState is not a function. I'm very new to ES6 Arrow functions but I tried to rewrite the promise call to use the new syntax - as I thought that using Arrow Functions automatically binds the context of this to the parent scope. However this hasn't solved the problem. What am I doing wrong? Any help appreciated!
foursquare.venues.getVenues(params)
.then(function(venues) {
const venueList = venues.response.venues
console.log(venueList);
this.setState({
venues: venueList // this returns this.setState is not a function
})
})
.catch(err => {
console.log(err);
});
(arg1, arg2, arg3) => { this.doSomething(); }
That notation create a function who inherit from the parent this automatically.
The other way is to save this in a constant that will be inherited.
const self = this;
function exemple() {
self.doSomething();
}
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
I am trying to set a variable declared at the beginning of the class (a boolean) to true once a callback is called, but I keep getting a TypeScript erorr.
Here is the error:
TypeError: Cannot set property 'nonReceived' of undefined
Here is my code:
finalizeToken(){
braintree.setup(JSON.parse(this.finalToken), 'dropin', {
container: 'dropin-container',
defaultFirst: true,
form: 'checkout-form',
onPaymentMethodReceived: function (obj) {
this.nonReceived = true;
localStorage.setItem('nonce', obj.nonce);
}
});
}
The brintree-setup connect to Braintree Payments, and awaits user payment info. Once they submit the form, I need the variable "this.nonReceived" to be set to true.
If you use ES5 syntax you could use function(){}.bind(this) to bind the callback with the context but with Typescript you can use ES6 syntax and use arrow function (parameters) => {function_body} which bind current context implicitly.
This question already has an answer here:
Cannot pass module functions to Page
(1 answer)
Closed 6 years ago.
i'm getting a ReferenceError when i call a function i defined myself inside the page.evaluate() of Phantom; what is the proper way to do that ?
for example:
function mySweetFunction(item) {
// process item....
}
page.evaluate(function(){
var item= document.getElementsById('item');
mySweetFunction(item);
});
then i'll get the error:
ReferenceError: Can't find variable: mySweetFunction
What is the proper way to do this ?
mySweetFunction is quite big, and i would prefer to keep it out of page.evaluate(...) if possible.
If you want to use a function inside page.evaluate() you have to put it there first:
page.evaluate(function(){
function mySweetFunction(item) {
// process item....
}
var item = document.getElementsById('item');
mySweetFunction(item);
});
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I have a very simple setup:
var genres;
$.get('/api/genres', '', function (response) {
genres = response.data
}, 'json');
$("#genre").tagit({
availableTags: genres //this doesn't work
});
For some reason the genres variable is not accessible inside the tagit method. How would I achieve this?
$.get is asynchronous. It's not that genres is not accessible inside .tagit. Your problem is that by the time you try to use it, it's still unassigned. A way to fix it would be moving your .tagit function inside the callback:
var genres;
$.get('/api/genres', '', function (response) {
genres = response.data
$("#genre").tagit({
availableTags: genres //this doesn't work
});
}, 'json');
I also recommend reading $.get's documentation.
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 8 years ago.
So I am calling a function within a view when a user clicks a button. This function requires a callback function. I have the callback defined within the same view. When The callback is called I want to render the current view with the additional info just obtained. However it seems like you lose scope within the callback function so that I get an error when calling this.render(); Saying "global object has not method render". So 'this' now refers to the window object. How do I retain scope within my view? So here is an example of what Im talking about.
var profileView = Parse.View.extend({
events: {
"click #scan_item": "scanItem"
},
scanItem: function(){
ScanItem(callback);
},
callback: function(info){
this.render(info);
},
render: function(info){
$(this.el).html(this.template({info: info}));
return this;
}
});
You need to bind your callback to the correct 'this'
Might work:
ScanItem(this.callback.bind(this))
(I don't know if this framework has a bind function)
Otherwise, old school :) Keep this in a variable in the enclosing scope
var that=this;
ScanItem(function(info){
that.callback(info)
});
Why does the function passed to scanItem need to be defined as though it was a "method"?
And should it have to know about the arguments being passed - why not just pass them all?
var that=this;
ScanItem(function(){
that.render.apply(that,arguments);
});