Is there anyway to calling a function from another function .. little hard to explain. heres in example. One function loads html page and when ready it calls the original function.
I think i need to pass in a reference but unsure how to do this... if i set it to "this" - it doesn't seem to work
ANy ideas?
order.prototype.printMe = function(){
order_resume.loadthis("myTestPage.html", "showData");
}
order.prototype.testme= function(){
alert("i have been called");
}
//Then when in "loadthis" need to call
orderRsume.prototype.loadthis= function(){
// DO SOME STUFF AND WHEN LOADS IT ARRIVES IN OnReady
}
order.prototype.OnReady= function(){
/// NEED TO CALL ORIGINAL "testme" in other function
}
It's not clear for me what you really want to do. In JS functions are first-class objects. So, you can pass function as a parameter to another function:
Cook("lobster",
"water",
function(x) { alert("pot " + x); });
order.somefunc = function(){
// do stuff
}
order.anotherone = function(func){
// do stuff and call function func
func();
}
order.anotherone(order.somefunc);
And if you need to refer to unnamed function from it's body, following syntax should work:
order.recursivefunc = function f(){
// you can use f only in this scope, afaik
f();
};
I slightly changed the signature of your loadthis function aloowing it to be passed the order to actually load.
I also assumed that your doSomeStuff function accepts a callback function. I assumed that it may be an AJAX call so this would be trivial to call a callback function at the end of the AJAX call. Comment this answer if you need more info on how to fire this callback function from your AJAX call.
order.prototype.printMe = function(){
order_resume.load(this, "myTestPage.html", "showData");
}
order.prototype.testme= function(){
alert("i have been called");
}
//Then when in "loadthis" need to call
orderRsume.prototype.load = function(order, page, action){
// DO SOME STUFF AND WHEN LOADS IT ARRIVES IN OnReady
doSomeStuff(page, action, function()
{
order.OnReady();
});
}
order.prototype.OnReady= function(){
/// NEED TO CALL ORIGINAL "testme" in other function
this.testme();
}
Related
I want to pass an anonymous function as a callback, then call it. I am probably missing something simple, but I just get the error 'Uncaught type error - callback is not a function'.
This is what I am doing - (using jQuery) - I pass the callback as an anonymous function when creating a new object:
$('#someid').alphaColorPicker({
callback: function() {
console.log("called")
}
});
Then I call it at some point (or try to):
$.fn.alphaColorPicker = function(callback) {
...
...
callback(); //this throws the error
}
How do I correctly call the callback function?
Thanks.
Look at the value you are sending:
{ callback: function () { ... } }
That isn't a function.
It is an object with a property called callback which is a function.
Therefore:
callback.callback();
Or you could pass an actual function instead of an object:
$('#someid').alphaColorPicker(function() { console.log("called") });
You are not directly passing the function, you are passing an object which has callback property
make it
$.fn.alphaColorPicker = function(options) {
...
options.callback(); //this throws the error
}
The thing you pass into the alphaColorPicker is not a callback function but rather a object containing a value that is a callback.
{ // When putting it within {} its a new object.
// Where 'callback' is a member/key of the object.
callback : function() {
console.log("called");
}
If you instead pass the function directly:
$('#someid').alphaColorPicker(function() {
console.log("called");
});
You can call it right away via callback();.
If you wish to keep it as an object, you can call it by calling the member of the object instead of trying to call the object as a function:
callback.callback();
Found the problem, should not have passed the function as
callback: function() {
console.log("called")
}
But just like this:
$('#' + boxID).alphaColorPicker(function() {
console.log("hello")
});
And if I want to pass parameters in, I can do it like this:
$('#' + boxID).alphaColorPicker({x:styleName, y:id, callback:function() {
//do something
}});
But I am confused about how to pass parameters in / out like in jQuery event handlers such as:
$("#"+boxID).alphaColorPicker({x:styleName, y:this.inputID}, function(e){}
});
How do you access the callback here? In my example, in alphaColorPicker callback.x and callback.y are obviously available, but the callback function is passed as an object I can't see how to call it.
If I want to break a callback implementation out of a method's parameter footprint for cleaner code I can do (for example)
foo.bar(a, callback(), b);
function callback() {
stuff;
}
instead of
foo.bar(a, function() {
stuff;
}, b);
But what do I do if the method passes something into the callback like three.js's loader functions? (http://threejs.org/docs/#Reference/Loaders/OBJMTLLoader)
foo.bar(callback(object));
function callback(object) {
object.stuff();
}
doesn't seem to work.
Got it. The format should be:
foo.bar(callback);
function callback(object) {
object.stuff();
}
The 2 snippets you've posted are actually different - when you pass an anonymous function as an argument it isn't run immediately, but in the "foo.bar" function itself. However, when you pass it as "callback()", that function runs immediately (it is useful in some cases, for example: if the function returns another function). So, pass it without "()".
For example:
function a(){
alert(1);
}
function b(callback){
callback(); //run the callback function.
}
b(a);
And, if you want to see an example of the second option:
function a(){
return function() {
alert(1);
};
}
a()(); //Alert
b(a()); //Alert
b(a) //nothing happens
In my application I need to conduct an IP lookup as a prerequisite to proceeding with execution of another function that needs that data. Originally, I called the function as follows:
$(document).ready(function(){
var ipUrl = "myURL?callback=?";
$.getJSON(ipUrl, function(data) {
window.ip = data['ip'];
console.log("inside function" + window.ip);
}).done(printIp());
});
function printIp() {
console.log("function is done " + window.ip);
}
However, this outputs as
function is done undefined
inside function <ip_address>
I.e. the printIp() function is called before the $.getJSON is actually complete.
If however, I wrap the printIp() call within an anonymous function as follows:
$.getJSON(ipUrl, function(data) {
window.ip = data['ip'];
console.log("inside function" + window.ip);
}).done(function() {
printIp();
});
I get:
inside function <ip_address>
function is done <ip_address>
As I would expect. What is going on here? Why do I need to wrap the function call in an anonymous function?
your code says
}).done(printIp());
what this does is calling printIp and using the result of the function call as an argument to the done method.
what you actually want is passing the function as a done handler. use }).done(printIp); to do this instead.
You are executing printIp right away. Try it without the ():
$.getJSON(ipUrl, function(data) {
window.ip = data['ip'];
console.log("inside function" + window.ip);
}).done(printIp);
pass the function without parantheses, otherwise you are calling it right away:
.done(printIp)
I need for a function to be executable only after an object is defined, I'm currently working in a fascade pattern and one method is dependent on another method. in this case 'addNewLayer' fails because 'setFullMap' hasn't finished executing. is there a solution? I'm using jquery and vanilla js so most any solution would be helpful at this point:
var jen = (function(){
function setFullMap(mapID){
jen.map = new Map(mapID);
}
function setLayer(opt){
//execute code here after jen.map is defined
}
return{
samp: function(id, opt){
setFullMap(id);
addNewLayer(opt);
}
};
})();
Thanks
solution:
var jen = (function(){
function setFullMap(mapID, callback) {
jen.map = new Map(mapID);
if(jen.map){
callback();
}
}
return {
samp: function(id, opt){
setFullMap(id, function(){
addNewLayer(opt);
}.bind(this));
}
};
})();
You will have to pass a callback function to setFullMap, and execute it once the function has completed (at the very end, before the closing }).
var jen = (function(){
function setFullMap(mapID, callback){
jen.map = new Map(mapID);
callback();
}
function setLayer(opt){
//execute code here after jen.map is defined
}
return{
samp: function(id, opt){
setFullMap(id, function() {
addNewLayer(opt);
}.bind(this));
}
};
})();
Do not forget using .bind(this) - it is very important in order to keep the original this in your callback function.
Edit:
Actually that would not work work if the Map constructor is a-synchronous. If you do not have access to the constructor and/or you cannot pass it a callback, then presumably the only (and sad) option would be to use a setTimeout or (easier) setInterval, continuously checking at defined intervals if the operation has been completed, and then fire the callback.
You could use a callback parameter:
function setFullmap(mapId,callback) {
jen.map = new Map(mapId);
callback();
}
....
samp: function(id, opt){
setFullMap(id,function() {
addNewLayer(opt);
});
}
When u dont have a way to manipulate the Map Object then u need to use a loop:
var loop=self.setInterval(function(){
if(jen.map) {
//execute code here after jen.map is defined
console.log(typeof jen.map);
window.clearInterval(loop);
}
},50);
Check jsfiddle:
http://jsfiddle.net/9yv5t/1/
I have checked the docs and it seems that there are various events you could listen to.
For example:
var m = new Map(...);
m.on('load', function () {
//execute code when the first layer is ready
});
var l = new Layer(...);
l.on('load', function () {
//execute code when the layer has been initialized
});
It's also carefully stated for the Layer.load event:
fires after layer properties for the layer are successfully populated.
This event must be successful before the layer can be added to the
map.
In short i want to overwrite a javascript function with a newer one, but in that newer function i want to be able to call the old one. So for example:
function test()
{
alert('original');
}
// then some time later
function test()
{
alert('new function');
}
// call function
test();
In this case only the last test() is invoked. So the new function is alerted.
But is there a way to call the first test() method aswell? SO both test() function get invoked?
The reason i need this is because a web application generates an onSave() method. This function is triggered when a form is saved through Ajax.
I want to do some additional things when the form is saved but i can't just change the original onSave() function. That is why i'm looking for a way to extend it.
How can i do this?
function test()
{
console.log('original');
}
var test = function (oldFn) {
// /\
// -------
// \/
return function () { // <- return a new function which will get stored in `test`
oldFn(); // use the passed `oldFn`
console.log('new function'); // the new code
};
}(test); // <- pass in the old function, we do this, to avoid reference problems
// call function
test();
Why don't you create a new function and put inside the function test() so that when the function test() is called then the new function is called too..
e.g.
function test(){
//code
your_new_function();
}
function your_new_function(){
//code
}
Use below instead of making same name function
$(document).ajaxComplete(function() {
// do your work
});
You can't create two functions of same name