有没有可能用一个功能取代两个相反的不同功能
Is it possible to replace two opposite and different functions with a single one?
我想优化和减少我的代码,以提高它的性能和正确性。有了下面这两个不同的功能,我可以使用在GPS坐标阵列上计算的pathIndex
成功地在地图上前后移动Google Map Marker
[我没有包括这段代码,因为我认为它与这个问题无关,但如果需要,我可以也会发布它]。
这是我的代码:
第一个功能:
function animate() {
if (pathIndex < coord.length && mapAnimationStatus != PLAY_PAUSED) {
googleMapsMarker.setPosition(coord[pathIndex]);
googleMap.panTo(coord[pathIndex]);
pathIndex += 1;
if (pathIndex == coord.length) {
pause();
pathIndex = 0;
mapAnimationStatus = NOT_PLAY;
return;
}
timerHandler = setTimeout("animate(" + pathIndex + ")", 1000);
}
}
第二个功能:
function animateRewind() {
if (pathIndex >= 0 && mapAnimationStatus != PLAY_PAUSED) {
googleMap.panTo(coord[pathIndex]);
googleMapsMarker.setPosition(coord[pathIndex]);
if (pathIndex == 0) {
pause();
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex -= 1;
timerHandler = setTimeout("animateRewind(" + pathIndex + ")", 1000);
}
}
正如你所看到的,这两个函数共享了很多代码部分,因此它认为可以用一个函数来替换它们,但我不知道如何做到这一点。
那么,有可能创建一个function
来管理这两个不同的动画吗?
我希望我没有错过什么。。。
function animate(pathIndex, dir) {
var animateDir = (pathIndex < coord.length
&& mapAnimationStatus != PLAY_PAUSED && dir == 'f')
? dir
: (pathIndex >= 0
&& mapAnimationStatus != PLAY_PAUSED && dir == 'r')
? dir : "error";
if (animateDir === "r") { googleMap.panTo(coord[pathIndex]); }
if (animateDir !== 'error') { googleMapsMarker.setPosition(coord[pathIndex]); }
if (animateDir === "f") {
googleMap.panTo(coord[pathIndex]);
pathIndex += 1;
}
if (animateDir !== 'error') {
if (pathIndex == coord.length || pathIndex == 0) {
pause();
pathIndex = animateDir === "f" ? 0 : pathIndex;
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex = animateDir === "f" ? pathIndex - 1 : pathIndex;
timerHandler = setTimeout("animate(" + pathIndex + "," + animateDir + ")", 1000);
}
}
你可以试试这个:
function ConcatenateFunctions() {
if(mapAnimationStatus != PLAY_PAUSED){
googleMap.panTo(coord[pathIndex]);
googleMapsMarker.setPosition(coord[pathIndex]);
if (pathIndex < coord.length) {
pathIndex += 1;
if (pathIndex == coord.length) {
pause();
pathIndex = 0;
mapAnimationStatus = NOT_PLAY;
return;
}
}else if (pathIndex >= 0) {
if (pathIndex == 0) {
pause();
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex -= 1;
}
timerHandler = setTimeout("ConcatenateFunctions(" + pathIndex + ")", 1000);
}
}
希望它能有所帮助!
相关文章:
- 两个按钮在初次点击后会触发相同的功能
- 如何将具有相同功能的两个select html标签的两个JS组合在一起
- 如何使用相同的按钮点击两个功能
- 两个功能合二为一 - 计算和提交表单
- 一个按钮中的两个onClick功能,并希望一个接一个地发生一个单击功能
- 消息在两个功能完成之前发送
- 防止两个默认功能发生,并同时触发第三个事件
- 如何将相同的功能应用于两个按钮
- 是否有任何功能可以合并两个JSON数据集并替换旧信息?(节点.JS)
- 如何将中的两个geoJSON功能集合添加到两个层组中
- 用于两个功能的Javascript按钮.提交&单击
- rails上的两个保存按钮的功能略有不同
- 一个ng点击按钮下的两个功能
- 这两个 Angular 控制器之间的功能有什么区别吗?
- 这两个功能有什么区别
- 有一个功能可以将字符串很好地缩短为一个、两个或三个字母
- (飞镖)我希望触发两个不同的onclick功能,具体取决于单击时是否选中了单选按钮.我该怎么做
- 一个 PHP 文件中有两个事件功能
- 组合具有不同初始设置的两个节点服务器的功能
- 如何在jQuery中单击两个按钮之一时执行功能