我现在已经学习 Javascript 8 个月了,5 个月前我找到了一份前端开发人员的工作,并且我已经更深入地参与了 javascript,这是我喜欢的事情。最近我注意到我的代码看起来很丑,因为是一堆函数和全局变量,所以我开始阅读一些关于设计模式的内容。现在我带来了一些对我有用的东西,但我不确定这是否是一个好习惯,无论如何我希望你们看看代码并告诉我我可以改进什么以及使用模块化加注星标的更好方法是什么javascript中的模式,如果你能建议我一些材料来学习模块化模式和Javascript。
JAVASCRIPT代码:
var responsiveModule = {
settings: {
device: false,
button: $(".responsive-btn"),
target: $("nav ul"),
mobileClass: "toggle-menu",
bgImage: '<img class="background-image" src="img/background.jpg" alt="">',
bgImageSelector: $(".background-image"),
windowWidth: $(window).width(),
},
init: function(){
responsiveModule.checkDevice();
responsiveModule.replaceImages();
responsiveModule.bindFunctions();
responsiveModule.listenResize();
},
checkDevice: function(){
if(this.settings.windowWidth > 992){
this.settings.device = "desktop";
} else {
this.settings.device = "mobile";
}
},
bindFunctions: function(){
var buton = this.settings.button,
muelleBtn = this.settings.muelleBtn;
buton.on("click touchstart", function(e){
e.preventDefault();
responsiveModule.animateMenu(responsiveModule.settings);
});
},
animateMenu: function(settings){
var device = settings.device,
target = settings.target,
mobileAnimation = settings. mobileClass;
if(device == "mobile"){
target.toggleClass(mobileAnimation);
}
},
replaceImages: function(){
var bgContainer = $("#main-content"),
bgImage = responsiveModule.settings.bgImage,
device = responsiveModule.settings.device,
backgroundSelector = $(".background-image");
if(device == "desktop" && backgroundSelector.length == 0){
bgContainer.append(bgImage);
}else if(device == "mobile" && backgroundSelector.length == 1){
backgroundSelector.remove();
}
},
listenResize: function(){
$(window).on("resize", function(){
responsiveModule.checkDevice();
responsiveModule.replaceImages();
responsiveModule.settings.windowWidth = $(window).width();
});
}
}
var tooltipModule = {
settings: {
tooltipState: false
},
init: function(){
tooltipModule.bindUIfunctions();
},
bindUIfunctions: function(){
var device = responsiveModule.settings.device;
if(device == "mobile"){
$(".ship").on("click", function(e){
e.preventDefault();
tooltipModule.manageTooltip(e);
});
}else{
$(".muelle-item").addClass("desktop");
}
},
manageTooltip: function(e){
var tooltip = $(e.currentTarget).next(),
tooltips = $(".tooltip");
tooltips.removeClass("display");
tooltip.addClass("display");
}
}
$(document).on("ready", function(){
responsiveModule.init();
tooltipModule.init();
});