It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am a beginner in javascript OOP. I'm trying to make an API to provide information stored in database. I didn't specifically used to use callbacks.
My constructor makes an asynchronous call (get_question function) so when I want to use my API :
var obj = new API('id');
obj.get_description();
my object is empty because there is no synchronization !
So,how to create a usable API in this way knowing that my constructor makes an asynchronous call?
Here is the code of my API class:
var API = function(question_id_algo) {
var id_algo = question_id_algo;
var self = this;
var question_object = null;
this.callback_db_init = function(data) {
question_object = data;
}
get_question(id_algo, self.callback_db_init);
this.get_description = function() {
if(question_object != null){
return question_object.description;
}
}
}
And my get_question function
function get_question(id_algo, callback_function)
{
Lungo.Data.Sql.select('question', {id_algo: id_algo}, callback_function);
}
I use Lungo.js framework to access my SQLite database.
You can't get a synchronous result from an asynchronous operation. Something here must take a callback: either the constructor or the accessor function. Placing it on the constructor probably makes the most sense (though it may vary, depending on your exact program structure):
var obj = new API('id', function() {
// this function runs when the API object is ready
this.get_question();
});
The code to achieve this would look like:
var API = function(question_id_algo, constructorArgCallback) {
//...
var apiObj = this;
this.callback_db_init = function(data) {
question_object = data;
constructorArgCallback.call(apiObj);
}
//...
}
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
In Airbnb JavaScript Style Guide, they mentioned "When saving a reference to this use _this."
// bad
function() {
var self = this;
return function() {
console.log(self);
};
}
// bad
function() {
var that = this;
return function() {
console.log(that);
};
}
// good
function() {
var _this = this;
return function() {
console.log(_this);
};
}
However, I read few books mentioned "self" is good. Like in AngularJS: Up and Running.
<script type="text/javascript">
angular.module('notesApp', []).controller('MainCtrl', [function () {
var self = this;
self.message = 'Hello ';
self.changeMessage = function () {
self.message = 'Goodbye';
};
}]);
</script>
So, could any one tell me the reason to use "_this" instead of "self"?
This is just personal preference. However, it's best to only use one option inside a project's codebase. So don't use _this in one function block, then that or self in the other..
As noted by others, this is purely a coding style preference. I would offer a suggestion: If your team's code base is interested in continuing to use lexical scoping for this, then consider using ES6's fat arrow function instead to avoid creating an unnecessary variable.
This of course all depends if your project is ready to implement ES6 features.
I would not use self as it is already in use as another pointer to the window object. See here (part way down page) for an example of using self like a variable (without needing to prefix it as window.self): https://developer.mozilla.org/en/docs/Web/API/Window/self
I am using http get function to get json array from service. How can I set response to controller locations element.
function MainCtrl($http,myService) {
this.locations = null;
myService.async().then(function(d) {
? = d;
});
}
Response d is well-formed (JSON)
You just take a reference to the current context and then use that variable reference in the callback
function MainCtrl($http,myService) {
var vm = this;
vm.locations = []; // initialise properly
myService.async().then(function(d) {
vm.locations = d;
});
}
There is a different approach to this problem too. I added my 'answer' for the sake of completeness. It is also possible to bind the this reference to your function. This can be achieved in two ways, by either using the angular.bind() or the native javascript bind to pass this reference.
e.g.:
function MainCtrl($http,myService) {
this.locations = []; // initialise properly
myService.async().then(function(d) {
this.locations = d;
}.bind(this));
}
P.S.: I tried to edited your answer and add this solutions to this problem of different scopes but it got rejected. For the following reason:
This edit was intended to address the author of the post and makes no sense as an edit. It should have been written as a comment or an answer
Not to take aim at the reviewers but they sure don't realize I can't post any comment with the current rep I have nor does it make sense to answer an answered question.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have two functions and am trying to return something from the second function. Not sure what I am doing wrong. I keep getting undefined in the alert.
function a(){
var testMe = b("hello");
alert(testMe);
}
function b(theVar){
var returnVar = theVar;
return returnVar;
}
as you can see here, is working: http://jsfiddle.net/hCGu8/
CODE
function a(){
var testMe = b("hello");
alert(testMe);
}
function b(theVar){
var returnVar = theVar + " returned";
return returnVar;
}
a();
This sound right to me... and in fact I happen to have "hello" in the alert:
function a(){
var testMe = b("hello");
alert(testMe);
}
function b(theVar){
var returnVar = theVar;
return returnVar;
}
a();
http://jsfiddle.net/u7zPY/
Your question subject says "Return from on function" and your tags mention jQuery, while the code in the question works fine.
I'm working on the assumption that you have reduced your test case too far and removed the problem from it (in future, please test your reduced test cases to ensure they still demonstrate the problem!) and that you actually have something like this:
function a() {
var result = jQuery('foo').on('click', function () { return 1; });
// ^^ This being the on function
}
… and you want result to equal 1.
This is impossible.
on just assigns an event handler to run later. The execution of a will finish before that event fires. You can't return anything from an event handler to the function that assigns it.
You can use a callback, in which you define a function to run when the data is available. This works in exactly the same was as the function you pass as the second argument to on:
function a(callback) {
var result = jQuery('foo').on('click', function () { callback(1); });
}
a(function (result) { alert(result); });
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I must have used someone's existing code as a framework, and I developed a jQuery/JavaScript application I now need to use. It works fine if invoked from within the following code but I need to pass values for nnn from elsewhere in the page. Because I don't understand jQuery structure well enough, my efforts so far have failed.
<script>
$(function() {
.
.
.
var BuildTree = function(centralID) {
...
}
BuildTree(nnn);
});
I want to do something like:
function BuildTree(...) {
...
}
Thanks!
You have a problem with scope, you're defining BuildTree inside the scope of the function you're passing to jQuery (or $ in this case).
This is a problem in terms of javascript and no jQuery, functions define a scope, what it means is that what you define inside a funcion lives inside of it.
function test() {
var variable = 2; //variable within the scope of test
}
variable //undefined
So, if you need to use it outside, you could define it outside the function and then use it inside or do something like:
$(function(){
...
window.BuildTree = BuildTree //global scope
...
});
Also be careful with the caps, it means you're defining a Constructor, by javascript standars
The scope of the BuildTree function is limited to the scope of the outermost function. You simply need to move the function definition outside of the $(function() { function.
var BuildTree = function(centralID) {
...
}
$(function() {
BuildTree(nnn);
});
BuildTree(nnn); // call it again.
There is no (major) difference between
var FunctionA = function () {
}
and
function FunctionA() {
}
Javascript has function scope, which means that variables defined inside of a function are not accessible outside of that function. Anything that is declared inside of the jQuery function will not be accessible outside of the function.
$(function() {
//anything defined in here will not be accessible outside of this jQuery function
var foo = 'bar';
var buildTree = function(centralId) {
};
});
//this will be undefined since it was declared inside of the jQuery function
buildTree(1);
//this will also be undefined
console.log(foo);
If you want to access the buildTree function, you need to do so inside of the jQuery function.
If BuildTree is just a function, you shouldn't need to put it inside $(function() {. You should just be able to do this:
<script>
function BuildTree(centralId) {
// do stuff
}
</script>
Now you should be able to call this function from anywhere in the page. If you want BuildTree to be invoked when the DOM finishes loading, just do this:
<script>
$(function() {
BuildTree(1234);
});
</script>
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Context
I am working on improving my JavaScript skills and I'm learning more about prototyping. I want to better understand the code in this question and any limitations or problems with it.
One thing that hasn't been obvious is defining more complex constructors that do more than simple initialization. What I want to do is have a Class that calls a web service when it's created without needing to call a method right after initialization.
What I did was create a property and assign a self calling anonymous method to it. It seems to work like I want it to, but I don't know if there is a better approach.
The Code
function AsyncOrderLine(productID) {
var context = this;
this.autoValue;
this._productID = productID;
this._asyncRequestComplete = false;
this.hello = function () {
alert("hello world");
}
this.constructor = (function () {
context.hello();
context.autoValue = "testing: " + productID + "(" + context._asyncRequestComplete + ")";
})()
}
The Result
var _asyncOrderLine = new AsyncOrderLine(1001);
Alert Shown: "Hello World"
_asyncOrderLine.autoValue = testing: 1001(false)
_asyncOrderLine.constructor = 'undefined'
In this case I want the constructor to remain undefined once the object is created.
Question
Is there a better way of doing this? Could there be any unforeseen side affects using this approach?
There's no need to complicate things like that. You can run whatever code you want inside your constructor:
function AsyncOrderLine(productID) {
this.autoValue;
this._productID = productID;
this._asyncRequestComplete = false;
this.hello = function () {
alert("hello world");
}
// Run whatever arbitrary code you want...
this.hello();
this.autoValue = "testing: " + productID + "(" + context._asyncRequestComplete + ")";
}
As others have said, there's no reason for the constructor property. You can just run whatever code you want in the function body and it will run at the time the object is initialized. If you want to run asynchronous code (like ajax calls), then you will probably want to pass a completion function into the constructor so the creator of the object can know when the asynchronous part of the object initialization is actually complete because it won't be complete when the object returns from it's initialization. That would look something like this:
function function AsyncOrderLine(productID, fn) {
// initialization code for the object here
this._asyncRequestComplete = false;
...
// kick of asychronous networking call here
var context = this;
$.getJSON(url, function(data) {
// process the data response into our object here
context.whatever = data;
context._asyncRequestComplete = true;
// call the completion function with `this` set to point to our object here
// so the creator of this object can know when the async part of
// initialization is actually done
fn.call(context);
});
}
And, then a caller would do something like this:
var x = new AsyncOrderLine(id, function() {
// can reference new object and it's methods and properties via "this"
alert("orderLine object is now completely initialized");
});