【问题标题】:Modular JS: How to run a non-global function模块化 JS:如何运行非全局函数
【发布时间】:2018-01-07 11:28:37
【问题描述】:

这是我的代码(简单):

<script type="text/javascript">

// Set Schedule 
(function() {
var schedule = {

    report: [], 
    template: $('#report_schedule').html(),

    init: function() {
        this.cacheDom();
        this.bindEvents();
        console.log("banana");
    }, 
    cacheDom: function() {
        this.$setScheduleBtn = $('#setScheduleBtn'); 
        this.$reportSchedule = $('#reportSchedule');
    }, 
    bindEvents: function(){
        console.log("potato");
        this.$setScheduleBtn.on('click', showReportScheduler.bind(this));
    }, 
    showReportScheduler: function(){
        this.$reportSchedule.toggle();
    },



    schedule.init();
};

})();
</script>

    <span class="btn" id="setScheduleBtn">Set Schedule</span>
    <div id="reportSchedule" name="reportSchedule" style="display: none;">

我正在运行它,但没有看到点击事件的结果。 我尝试在我的 init 函数中使用 console.log("banana"); 只是为了确保该脚本正在运行。我的浏览器控制台中没有香蕉。 我不明白什么?

ps:这是我第一次自己尝试模块化 js。

编辑:

感谢提图斯的帮助。这是我的最终代码:

    <span class="btn" id="setScheduleBtn">Set Schedule</span>
    <div id="reportSchedule" name="reportSchedule" style="display: none;">
        ......  
    </div>

<script type="text/javascript">
/******************/
/** Set Schedule **/ 
/******************/
(function() {

    var schedule = {

        report: [], 
        template: $('#report_schedule').html(),

        // Init functions
        init: function() {
            this.cacheDom();
            this.bindEvents();
        }, 
        // Cache elements from DOM
        cacheDom: function() {
            this.$setScheduleBtn = $('#setScheduleBtn'); 
            this.$reportSchedule = $('#reportSchedule');
        }, 
        // Set events
        bindEvents: function() {
            this.$setScheduleBtn.on( 'click', this.showReportScheduler.bind(this) );
        }, 
        // Display on click
        showReportScheduler: function() {
            this.$reportSchedule.show("slow");
        }

    };
    schedule.init();

})();
</script>

【问题讨论】:

    标签: javascript modular-design


    【解决方案1】:

    schedule.init(); 语句位于对象字面量内。 您需要将其移到对象字面量之外,但将其保留在函数内:

    (function() {
        var schedule = { // object literal start
             ......
        };// object literal end
    
        schedule.init();
    
    }/* function end */)();
    

    【讨论】:

    • 非常感谢!但总而言之,我的点击事件没有启动。知道为什么吗? ReferenceError: showReportScheduler is not defined
    • @RickSanchez 你必须使用this.showReportScheduler.bind(this)
    • @RickSanchez 此外,您可能必须等到 DOM 准备好。您可以通过将代码包装在 $(function(){}) 而不是 (function{})() 中来做到这一点。
    • 我使用了 bind 但仍然得到相同的结果(我确实希望它在我的 html 加载后立即运行,而不是等到整个页面加载完毕)。
    • @RickSanchez 是的,这就是问题所在,那个版本没有on 功能。这是一个使用该版本并产生相同错误的小提琴jsfiddle.net/gmpw3qyf
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    相关资源
    最近更新 更多