[英]Modular JS: How to run a non-global function
這是我的代碼(簡單):
<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函數中只是為了確保該腳本正在運行。 我的瀏覽器控制台中沒有香蕉。 我不明白什么?
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>
schedule.init();
語句位於對象文字內部。 您需要將其移到對象文字之外,但要保留在函數中:
(function() {
var schedule = { // object literal start
......
};// object literal end
schedule.init();
}/* function end */)();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.