我正在使用 DHTMLX-touch 框架(基本上是 javascript)为移动设备开发应用程序。
我有一个实现此功能的 A 类:
A.prototype.initEventHandler = function(controller) {
$$('btn_submit').attachEvent('onItemClick', controller.switchView($$('ui_ewmon_main')));
}
第一次实现
对象 Controller 是B类的一个实例,B类如下:
function B() {
//back button management
this.last_view=new Array();
this.current_view=this.ewmon_view.getRoot();
this.switchView = function(next) {
this.last_view[this.last_view.length]=this.current_view;
this.current_view=next;
next.show();
}
}
使用 Firebug 我得到这个错误:
A.js:32Uncaught TypeError: Object # has no method 'switchView'
二次实现
如果我尝试将 switchView 函数定义为原型(prototype)函数:
function B() {
//back button management
this.last_view=new Array();
this.current_view=this.ewmon_view.getRoot();
}
B.prototype.switchView = function(next) {
this.last_view[this.last_view.length]=this.current_view;
this.current_view=next;
next.show();
}
在这种情况下,我得到以下错误:
B.js:13Uncaught TypeError: Cannot read property 'length' of undefined
谁能帮帮我?
提前致谢 达尼洛
最佳答案
您正在调用 attachEvent
并返回 controller.switchView($$('ui_ewmon_main'))
,以获得您想要的结果:
A.prototype.initEventHandler = function(controller) {
$$('btn_submit').attachEvent('onItemClick', function(){ controller.switchView($$('ui_ewmon_main')); });
}
编辑:
查看您发布的代码,我预计会出现此错误。从 this.current_view=this.ewmon_view.getRoot();
行,我们会猜测 this.current_view
始终是一个对象,类似于 EWmonView.prototype 返回的对象.getRoot
(正确?),但此对象没有方法 show
。
但是您调用 controller.switchView($$('ui_ewmon_main'));
导致 this.current_view
成为 $$('ui_ewmon_main' )
,在数组this.last_view
和this.current_view
中保留不同的对象类型是错误的根源。
肮脏的修复将是:
if (this.current_view.show) {
this.current_view.show();
} else{
$$('ui_ewmon_main').show(); //or $$('ui_ewmon_login').show() can tell what you want =)
}
在 EWmonController 中出现 this.current_view.show();
的地方。但是重写代码并让 this.current_view
始终具有相同类型的对象对我来说看起来更好。
关于javascript - 如何在 Javascript 中的不同对象之间调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7836714/