我有一个很大的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... -->
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', 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:某些东西不是构造函数
我该如何做我想要的事情?有可能吗?
答案 0 :(得分:1)
确保先运行externalHandlers
,以便在运行handlerFunction
时定义example.js
,以便example.js
可以正确引用handlerFunction
,并且不会出错,并且以便正确定义Something
:
<script src="externalHandlers.js"></script>
<script src="example.js"></script>
答案 1 :(得分:0)
尝试此代码。
<script type="text/javascript" src="externalHandlers.js"></script>
<script type="text/javascript" src="example.js"></script>
<script>
$(document).ready(function(){
var something = new Something('someValue');
});
</script>