0

这是我的代码(简单):

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

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

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

1 回答 1

3

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

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

    schedule.init();

}/* function end */)();
于 2018-01-07T11:36:21.180 回答