Ich habe eine einfache apps mit viel Javascript-Code erstellt, ich benutze auch jQuery und der Code sieht so dreckig. Jetzt möchte ich versuchen, meinen Code auf Objektorientiert umzustrukturieren. Was ich verwirrt habe, ist, wo man eine Eigenschaft aufruft, wo man eine Benutzeraktion auf ein Element setzt, wo man eine dom-Elementvariable setzt usw. Es ist ein bisschen von meinem Code vor und nach der Neustrukturierung.Animierte Wolken und Flugzeug
Bevor:
var $cloud = $(".js-cloud");
var $plane = $(".js-plane");
function randomPosition(min, max) {
return Math.random() * (max - min) + min;
}
$cloud.each(function(){
var leftPosition = randomPosition(1,100) + "%";
$(this).css("left",leftPosition)
var speed = $(this).data("speed");
$(this).velocity({
left : "-200px"
}, {
duration : speed,
easing : "linear",
loop : true
})
})
function loopPlane(){
$plane.velocity({
left : "-300px"
}, {
duration : 7000,
easing : "linear",
complete : function(){
$(this).css({
"right" : "-300px",
"left" : "auto"
})
loopPlane()
},
delay : 15000
})
}
loopPlane()
Nach:
//Clouds and plane element
var $cloud = $(".js-cloud");
var $plane = $(".js-plane");
/* Module */
var background = {
init : function(){
this.loopClouds();
this.loopPlane();
},
randomPosition : function(min,max){
return Math.random() * (max - min) + min;
},
loopPlane : function(){
var obj = this;
//Animate it
$plane.velocity({
left : "-300px"
}, {
duration : 7000,
easing : "linear",
complete : function(){
$plane.css({
"right" : "-300px",
"left" : "auto"
})
obj.loopPlane()
},
delay : 1000
})
},
loopClouds : function(){
var obj = this;
$cloud.each(function(){
var leftPosition = obj.randomPosition(1,100) + "%";
$(this).css("left",leftPosition)
var speed = $(this).data("speed");
//Animate it
$(this).velocity({
left : "-200px"
}, {
duration : speed,
easing : "linear",
loop : true
})
})
}
}
Ist das mein Code sieht Reiniger und lesbar? oder gibt es eine bessere Version meines Umstrukturierungscodes?
sieht gut aus mit mir, nur der Name der Klasse "Hintergrund", die ich ändern sollte. Exemple backgroundAnimation. –