var myNamespace = {
dateController: {}
};
myNamespace.dateController = function(callback) {
this.callbackfunction = callback;
try {
[this.callbackfunction]();
} catch (e) {
alert(e);
}
};
function displayDate() {
alert("displayDate");
myNamespace.dateController("displayDateFromController");
};
function displayDateFromController() {
alert("In displayDateFromController");
};
This piece of code is giving me TypeError: ["displayDateFromController"] is not a function
error. What could be root cause and possible solution to this issue.
Why dateController not able to identify displayDateFromController
as function.
I have tired this on http://www.w3schools.com/js/tryit.asp?filename=tryjs_events
You need to pass the actual function to the datecontroller
method instead of the String
.
var myNamespace = {
dateController: {}
};
myNamespace.dateController = function (callback)
{
this.callbackfunction = callback;
try{
//remove [] surrounding function
this.callbackfunction();
}
catch(e)
{
alert(e);
}
};
//Declare this method prior to displayDate
function displayDateFromController()
{
alert("In displayDateFromController");
};
function displayDate()
{
alert("displayDate");
//Pass function instead of string
myNamespace.dateController(displayDateFromController);
};
displayDate();
Working Example: http://jsfiddle.net/RDMHV/
If you still need the flexibility of a String:
var myNamespace = {
dateController: {}
};
myNamespace.dateController = function (callback)
{
this.callbackfunction = this[callback];
try{
this.callbackfunction();
}
catch(e)
{
alert(e);
}
};
myNamespace.displayDateFromController = function(){
alert("In displayDateFromController");
};
function displayDate()
{
alert("displayDate");
myNamespace.dateController("displayDateFromController");
};
displayDate();
Working Example http://jsfiddle.net/RDMHV/1/
You have to remove the brackets around the call :
try{
this.callbackfunction();
}
catch(e)
{
alert(e);
}
and to pass the function without the quotes :
function displayDate()
{
alert("displayDate");
myNamespace.dateController(displayDateFromController);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.