首页 > 解决方案 > 调用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 不是构造函数

我怎么能做我想做的事情?这是可能的?

标签: javascriptjquery

解决方案


确保externalHandlers首先运行,以便在运行handlerFunction时定义example.js,以便example.js可以正确引用handlerFunction而不会出现错误,从而Something正确定义:

<script src="externalHandlers.js"></script>
<script src="example.js"></script>

推荐阅读