javascript - 调用javascript处理程序的正确方法
问题描述
我有一个巨大的JS文件,想分割它,例如我有这个:
page.html
<!-- some tags and jquery include... -->
<script src="example.js"></script>
<!-- externalHandlers only needs for second example, in original working example It's empty -->
<script src="externalHandlers.js"></script>
<script>
$(document).ready(function(){
var something = new Something('someValue');
);
</script>
<!-- some tags... -->
例子.js
var Something = (function (document) {
"use strict";
var Something = function(x){
//initialize some stuff
};
Something.prototype.func1 = function(){
//do things
}
Something.prototype.func2 = function(){
//do things
}
//more funcs
$(document).on('click', 'a.some-class', function (e) {
//do things when click
});
$(document).on('click', 'a.some-class-2', function (e) {
//do things when click
});
return Something;
})(document);
上面的代码工作正常,但我想在另一个 js 文件中外部化点击处理程序。我试过这个:
example.js(新)
var Something = (function (document) {
"use strict";
var Something = function(x){
//initialize some stuff
};
Something.prototype.func1 = function(){
//do things
}
Something.prototype.func2 = function(){
//do things
}
//more funcs
$(document).on('click', 'a.some-class', handlerFunction);
$(document).on('click', 'a.some-class-2', function (e) {
//do things when click
});
return Something;
})(document);
externalHandlers.js
function handlerFunction(){
//do some stuff
}
但是浏览器控制台显示错误
ReferenceError: handlerFunction 未定义
TypeError:Something 不是构造函数
我怎么能做我想做的事情?这是可能的?
解决方案
确保externalHandlers
首先运行,以便在运行handlerFunction
时定义example.js
,以便example.js
可以正确引用handlerFunction
而不会出现错误,从而Something
正确定义:
<script src="externalHandlers.js"></script>
<script src="example.js"></script>
推荐阅读
- office-interop - Outlook 新邮件 - 工具栏下方的文本区域
- javascript - 是否可以模拟 isTrusted=true
- javascript - 将数据目标作为道具传递
- mysql - 分区 SQL 表
- c# - Unity中使用ZXing定位二维码的位置模式
- c# - 映射数据类型 Oracle 和 C# 时出错
- android - 我在更新 android studio 3.1.2 时遇到了这个问题
- android - Android 连接到非活动网络
- delphi - 大型 Delphi exe 和维护问题
- java - 使用 JAVA 实现 NETIQ IDAM LDAP