Can't use variable from anonymous function outside scope in javascript [duplicate] - javascript

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.

Related

Why is a javascript function unaccessible from another script file? [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 5 years ago.
I have a problem I've been searching SO for answers to, but nothing seem to do it for me. I've referenced a question that mimics my problem but the solution still don't solve my problem.
Accessing function in another .js file with $.getScript
My problem is as I've mentioned similar. I can't access a method inside a script file from another script file. These are my codes:
page.js
$(document).ready(function () {
$.getScript('script.js').done(function () {
$('#build').append(literals.test()); // $('#build') is a span tag in the HTML-file.
}).fail(function () {
console.warn('Unable to load script file.');
});
});
script.js
(function ($) {
var literals = {
test: function () {
return 'Hello world!';
}
};
})(jQuery);
This still returns the following error even though I've built it almost exactly the same way as in the answer of the referenced question.
Uncaught ReferenceError: literals is not defined at Object.<anonymous>
What am I doing wrong here?
Because when you create a closure, anything inside of it is only visible to other things in that scope.
In JS, all functions are closures.
(function(){
// this is a closure
})()
If you want to be able to get the literals functions from outside of the closure, one option is to return it from the function...
const literals = (function($){
return {
test: function () {
return 'Hello world!';
}
};
})(jQuery);
console.log(literals.test());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How do I set the correct 'this' Lexical Scope when using Promises in ES6/React [duplicate]

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();
}

exctracting a variable from a jquery method [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I want to extract the variable response from the mentionsInput() method and using it outside this method, but when I try an alert() on this variable it's empty.
jQuery(document).ready(function() {
var choix = $('#choixaide').val();
var choix_sous_theme1 = $('#choix_sous_theme1aide').val();
$('textarea.mention1').mentionsInput('val', function(text) {
var response = text;
});
alert(response);
});
Thanks for your help.
As you have it now, response is only available within the scope of your mentionsInput method, but not outside of it.
Additionally, when running your code, I see the following error:
Uncaught TypeError: $(...).mentionsInput is not a function"...
Are you sure you've properly loaded the jquery.mentionsInput UI component? You'll need to solve for this error first, if you are also encountering this.
Then, you'll need to declare the variable response prior to and outside of your mentionsInput method, and then set it within mentionsInput. The value set for response should then be available in the same scope as your alert call.
I think this should do the trick:
jQuery(document).ready(function() {
var choix = $('#choixaide').val();
var choix_sous_theme1 = $('#choix_sous_theme1aide').val();
var response = $('textarea.mention1').val();
alert(response);
});

PhantomJS: call a user defined/custom function within phantomjs [duplicate]

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);
});

Context inside Promise.resolve() / Backbone [duplicate]

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;
})

Categories

Resources