[英]Javascript- Callback function issue from namespace?
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. 这段代码给了我
TypeError: ["displayDateFromController"] is not a function
错误。 What could be root cause and possible solution to this issue. 什么可能是根本原因,也可能是此问题的解决方案。
Why dateController not able to identify displayDateFromController
as function. 为什么dateController无法确定
displayDateFromController
的功能。
I have tired this on http://www.w3schools.com/js/tryit.asp?filename=tryjs_events 我已经在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
. 您需要将实际函数传递给
datecontroller
方法,而不是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/ 工作示例: http : //jsfiddle.net/RDMHV/
If you still need the flexibility of a String: 如果仍然需要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/ 工作示例 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);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.