Call functions inside of another function - javascript

I am having a problem calling functions inside a function.
This is the sample code:
<script>
function saveInfo() {
function returnEmail() {
var _e = document.getElementById("email").value;
return _e;
}
function returnName() {
var _n = document.getElementById("name").value;
return _n;
}
}
</script>
The saveInfo() method is made in a button:
<input type="submit" value="Save" onclick="saveInfo()" style="color: black">
So there are 2 forms, where you fill up your email and name. By clicking "Save" -button, the DIV will disappear (this works) and another DIV will appear within text like this: Name = (name) | Email = (email).
I am having problems to call the saveInfo()'s returnEmail() for the corresponding line (where there is 'Name = ').
I try to write them like this:
<p>Email:
<script>
var pEmail = saveInfo().returnEmail();
document.write(pEmail);
</script> <br>
</p>
I know that the script above is incorrect, this is not the only way I have tried to return it.

It looks like you're trying to return those functions to use later. Try doing this instead. This function now returns an object with two functions.
function saveInfo() {
return {
returnEmail: function() {
var _e = document.getElementById("email").value;
return _e;
},
returnName: function() {
var _n = document.getElementById("name").value;
return _n;
}
}
}
Previously, your saveInfo function wasn't returning anything, so
saveInfo().returnEmail();
would evaluate to
undefined.returnEmail();
and you'd get an error

You need to return the exposed functions from the function saveInfo. At this time, your code only declares the function, but doesn't return anything. So, saveInfo returns undefined. Below approach is an implementation of the Revealing module pattern to reveal the public members outside your function.
function saveInfo() {
var returnEmail = function () {
var _e = document.getElementById("email").value;
return _e;
}
var returnName= function () {
var _n = document.getElementById("name").value;
return _n;
}
return {
returnEmail :returnEmail,
returnName :returnName
}
}

If your set on calling it like saveInfo().returnEmail(); then you can do the following. saveInfo returns an object containing the returnEmail method.
<script>
function saveInfo() {
// Do any desired logic
return {
returnEmail: function() {
var _e = document.getElementById("email").value;
return _e;
},
returnName: function() {
var _n = document.getElementById("name").value;
return _n;
}
}
}
</script>

Related

How to wrap Javascript function within function expression?

I would like to add a wrapper function to one of my functions to show extra information.
Below is my wrapper function:
var wrap = function(functionToWarp, before) {
var wrappedFunction = function() {
if (before) before.apply(this, arguments);
result = functionToWrap.apply(this, arguments);
return result;
}
return wrappedFunction;
}
var beforeFunc = function(){
// print extra infos before functionToWarp() triggers.
}
and my function _printSth to wrap:
var Printer = function () {
this._printSth = function (input) {
// print something from input...
}
}
Printer._printSth = wrap(Printer._printSth, beforeFunc);
I have tried to wrap Printer._printSth by calling
Printer._printSth = wrap(Printer._printSth, beforeFunc); or similar codes but failed.
How should I declare my _printSth() to be able to be wrapped?
You could write
function Printer() {
this._printSth = function (input) {
// print something from input...
};
this._printSth = wrap(this._printSth, beforeFunc);
}
or
function Printer() {
this._printSth = wrap(function (input) {
// print something from input...
}, beforeFunc);
}
but that's equivalent to simply writing
function Printer() {
this._printSth = function (input) {
beforeFunc(input);
// print something from input...
};
}
Assuming you rather might want to wrap the method on a specific instance, you'd do
const p = new Printer();
p._printSth = wrap(p._printSth, beforeFunc);
Altering a method is done like that:
Printer.prototype._printSth = wrap(Printer.prototype._printSth, beforeFunc);

Why is window.onload function undefined?

I have made a simple function and it is supposed to run on window.onload. But instead, I get that it is undefined. Can anyone help me understand why I get this error?
The form id is kalkulator and the name of the inputs is liter and enheter
The function I have written is
window.onload = function () {
form.kalkulator.focus();
};
I have also written this
form.kalkulator = function () {
if (form.enheter.value == "") {
form.liter.value = "";
} else{
convertLiter();
};
}
function convertLiter() {
console.log(form.liter.value / person.volum() * person.sukker_g())
form.enheter.value = form.liter.value / person.volum();
}
function convertEnheter() {
console.log(form.enheter.value * person.sukker_g())
form.liter.value = form.enheter.value * person.volum();
}
This has nothing to do with window.onload.
You're invoking this...
form.kalkulator.focus();
but form.kalkulator is a function, it doesn't have a .focus() method. form.klalkulator.focus is undefined, and you're attempting to invoke it as a function, hence your error.
form.kalkulator doesn't have any return so you can't call
form.kalkulator.focus();
replace the function
form.kalkulator = function () {
if (form.enheter.value == "") {
form.liter.value = "";
} else{
convertLiter();
};
return form;
}
or split the instructions;
form.kalkulator();
form.focus();

using revealling moduler pattern for complex in javascript

I have a very complex class so i decided to break into sub modules and trying to use revealing modules pattern.
I have main class and decided to divide into smaller container function. but in current scenario
But i am not able to access any internal function from outside i.e callSearchResultWithCallBack using searchFinder.Search.callSearchResultWithCallBack(). which pattern should i use to keep this code clean as well have control to call internal function in sub module.
Thanks
var searchFinder;
function SearchFinder() {
me = this;
this.searchResult = null;
this.init = function() {
declareControls();
createAccordian();
addEvents();
fillControls();
var declareControls = function() {
this.SearchButtons = jQuery('.doSearch');
this.InputLocation = jQuery('#inputLocation');
this.InputDistanceWithIn = jQuery('#inputDistanceWithIn');
this.InputName = jQuery('#inputName');
}
var addEvents = function() {
me.SearchButtons.click(function() {
me.Search();
});
}
var fillControls = function() {
var getGetCategory = function() {
}
}
}
this.Search = function() {
var url = '';
var searchCriteria = {};
validateAndCreateCriteria();
callSearchResultWithCallBack();
function validateAndCreateCriteria() {
function validateAandGetCategory() {
if (SearchValidation.ValidateZipCode(me.InputLocation.val().trim())) {
searchCriteria.location = me.InputLocation.val().trim();
} else if (SearchValidation.ValidateCityState(me.InputLocation.val().trim())) {
searchCriteria.location = me.InputLocation.val().trim();
}
}
}
// need to access it outsite
function callSearchResultWithCallBack() {
me.searchResult(searchCriteria, SearchResultCallBack);
function SearchResultCallBack() {
}
}
}
}
jQuery(function() {
searchFinder = new SearchFinder();
searchFinder.init();
searchFinder.Search.callSearchResultWithCallBack();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
This code has multiple issues, first I will address the fact that for example declareControls is not executing. First declare the function than execute!
this.init = function() {
var declareControls = function() {
this.SearchButtons = jQuery('.doSearch');
this.InputLocation = jQuery('#inputLocation');
this.InputDistanceWithIn = jQuery('#inputDistanceWithIn');
this.InputName = jQuery('#inputName');
}
var addEvents = function() {
this.SearchButtons.click(function() {
me.Search();
});
}
var fillControls = function() {
var getGetCategory = function() {
}
}
declareControls();
//createAccordian(); //not defined
addEvents();
fillControls();
}
Now let's look at others problems that will arise.
the me object referring to this is in the scope of searchFinder and does not refer to the same this in the instance of searchFinder.
function jQuery can be replaced by the commonly used $.
searchFinder.Search.callSearchResultWithCallBack() this is never going to work. Since the Search function is an object and callSearchResultWithCallBack isn't a property of this function.
Solution; make it part of the prototype of Search.
Steps:
Move callSearchResultWithCallBack outside the search function.
Add prototype to Search function
Call function via prototype.
function callSearchResultWithCallBack() {
me.searchResult(searchCriteria, SearchResultCallBack);
function SearchResultCallBack() {
}
}
this.Search.prototype.callSearchResultWithCallBack = callSearchResultWithCallBack;
If you want to fire this function outside of search use this:
searchFinder.Search.prototype.callSearchResultWithCallBack();
Please remember that callSearchResultWithCallBack will throw an error because searchCriteria is undefined.
This fixes your problems for now, but this code has to be revised thoroughly. But this should get you started. http://ejohn.org/blog/simple-javascript-inheritance/

Two callback functions inside a function not called synchronously

function sample() {
var callback_1 = request1(function(response) {
var Name = response.name;
});
var callback_2 = request2(function(response_1) {
if (response_1.name === Name) {
// do something
});
}
}
I've two callback functions as shown above, callback_1 & callback_2 which requests a JSON from the service.
The callback_2 is called before callback_1 and variable Name is shown as undefined. Any help much appreciated,
How can I let callback_1 executed before callback_2 so that variable Name is not undefined.
Try this:
function sample() {
var callback_1 = request1(function(response) {
var Name = response.name;
var callback_2 = request2(function(response_1) {
if (response_1.name === Name) {
// do something
}
});
});
}
jQuery ajax request return a deferred object (assumming request1 and request2 are ajax calls of some sort). Take a look at http://api.jquery.com/category/deferred-object.
You can use something along the lines of:
function sample() {
var Name;
var callback_1 = request1(function(response) {
Name = response.name;
});
callback_1.then(
callback_2 = request2(function(response_1) {
if (response_1.name === Name) {
// do something
};
})
);
}

Javascript concatenate a function similar to how text can be added

In javscript we can do this
var text = "the original text";
text+=";Add this on";
If a library has a function already defined (e.g)
//In the js library
library.somefunction = function() {...};
Is there a way to add something on so that I can have two functions run?
var myfunction = function() {...};
Something like:
library.somefunction += myfunction
So that both myfunction() and the original library.somefunction() are both run?
You can use this kind of code (leave scope empty to use default scope):
var createSequence = function(originalFn, newFn, scope) {
if (!newFn) {
return originalFn;
}
else {
return function() {
var result = originalFn.apply(scope || this, arguments);
newFn.apply(scope || this, arguments);
return result;
};
}
}
Then:
var sequence = createSequence(library.somefunction, myFunction);
I think what you want to create is a Hook (function) - you want to call library.somefunction but add a bit of your own code to run before. If that's the case, you can make your myfunction either call or return the library function after it's done with your bit of code.
var myfunction = function() {
// your code
// ...
return library.somefunction();
}

Categories

Resources