简体   繁体   中英

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"); in my init function just to make sure this script is running. no bananas in my browsers console. What am I not understanding?

ps: this is my first time trying modular js by myself.

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(); 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 */)();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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