【发布时间】:2017-01-19 08:04:37
【问题描述】:
我已经创建了一个简单的应用程序,有很多 Javascript 代码,我也使用 jQuery,代码看起来很脏。所以现在,我想尝试将我的代码重构为面向对象。我困惑的是在哪里调用属性,在哪里对元素放置用户操作,在哪里放置 dom 元素变量等。这是我重构前后的一些代码。
之前:
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()
之后:
//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
})
})
}
}
我的代码看起来更干净可读吗?还是我的重构代码有更好的版本?
【问题讨论】:
-
对我来说看起来不错,只是我应该更改的“背景”类的名称。例如背景动画。
标签: javascript jquery object animation