简体   繁体   English

模块化JS:如何运行非全局函数

[英]Modular JS: How to run a non-global function

This is my code (simple): 这是我的代码(简单):

<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;">

I am running this and see no results on the click event. 我正在运行此程序,但单击事件没有结果。 I tried using a console.log("banana"); 我尝试使用console.log("banana"); in my init function just to make sure this script is running. 在我的init函数中只是为了确保该脚本正在运行。 no bananas in my browsers console. 我的浏览器控制台中没有香蕉。 What am I not understanding? 我不明白什么?

ps: this is my first time trying modular js by myself. ps:这是我第一次自己尝试模块化js。

Edit: 编辑:

Thank you Titus for your help. 谢谢提多斯的帮助。 this is my final code: 这是我的最终代码:

    <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>

The schedule.init(); schedule.init(); statement is inside the object literal. 语句位于对象文字内部。 You need to move it outside the object literal but keep it inside the function: 您需要将其移到对象文字之外,但要保留在函数中:

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

    schedule.init();

}/* function end */)();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM