1 回答
TA贡献1877条经验 获得超6个赞
您可以通过更新当前的模块模式来解决此问题,例如:
// This is our main Component module
//---------------------------------------------------
var Component = (function() {
// All private variables here
//---------------------------------------------------
var $blog;
// Place initialization logic here
//---------------------------------------------------
var init = function() {
console.log('Inside init()')
cacheDom();
bindEvents();
};
// Cache all required DOM elements here
//---------------------------------------------------
var cacheDom = function() {
//Initialize properties
console.log('Inside cacheDom()')
$blog = $('#blog');
};
// All event handler setup here
//---------------------------------------------------
var bindEvents = function() {
//setup eventhandlers
console.log('Inside bindEvents()')
$blog.on('click', function1);
};
// All other methods here
//---------------------------------------------------
var function1 = function(event) {
//do some work here
};
// Return the methods you want to make public
//---------------------------------------------------
return {
init,
};
})();
$(document).ready(function() {
console.log('Inside document.ready()')
Component.init();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
使用此模块,我们确保Component.init()仅在 DOM 完全准备好时才调用它。关于这种模式的一个更有趣的事情是,我们现在只能init()从外部访问公共方法,而所有其他私有方法,如cacheDom(),bindEvents()都不能从外部访问。从而Component.cacheDom();将返回undefined。我认为除了init()您不需要公开任何其他方法,因为您的所有逻辑现在都将在Component模块内处理。
添加回答
举报