我有以下情况:
var count = something.length;
google.maps.event.addDomListener( div, 'click', function( event ) {
for( a = 0; a < count; a++ ) {
// action 1
}
});
google.maps.event.addDomListener( div, 'mouseover', function( event ) {
for( a = 0; a < count; a++ ) {
// action 2
}
});
google.maps.event.addDomListener( div, 'mouseout', function( event ) {
for( a = 0; a < count; a++ ) {
// action 3
}
});我有几种类似的情况,而且我的循环似乎太多了。
如您所见,所有循环都通过相同的数组循环,但是操作是不同的。
我能解决类似的情况,只有一个循环/循环循环吗?
发布于 2016-01-18 14:21:00
不确定您所说的“循环”循环是什么意思,但这看起来更好一些。我认为把所有的循环组合在一起不会有什么收获
var count = something.length;
function loopFunc(action){
for( a = 0; a < count; a++ ) {
action();
}
}
function addMapLoopEvent(eventName,action){
google.maps.event.addDomListener( div, eventName, function( event ) {
loopFunc(action)
});
}
addMapLoopEvent('click', action1));
addMapLoopEvent('mouseover', action2));
addMapLoopEvent('mouseout', action3)); 发布于 2016-01-18 14:17:58
只有当循环或多或少同时发生时,才能有效地组合它们:
for (a=1;a<10;a++) {
// action a
}
for (b=1;b<10;b++) {
// action b
}变成:
for (a=1;a<10;a++) {
// action a
// action b
}这里的情况并非如此。您有三个相互排斥的不同事件。只要动作有很大的不同--也就是说没有太多重复的代码--把它们组合起来没有好处。实际上,就可读性而言,它可能是一个_dis_advantage。
使问题更加复杂的是,与jQuery的on方法不同,.使您不得不编写一个自定义循环来拆分事件字符串,然后使用event.type来运行适当的循环,从而使代码更加复杂,而没有明显的好处。
发布于 2016-01-18 14:16:49
你可以这样做:
var count = something.length;
function customCallback(callback) {
for( var a = 0; a < count; a++ ) {
if(typeof callback == 'function') {
callback();
}
console.log(count + ' => ' + a)
}
}
function someAction(msg) {
console.log(msg);
}
google.maps.event.addDomListener( div, 'click', function( event ) {
customCallback(); // will output your console.log from customCallback function
});
google.maps.event.addDomListener( div, 'mouseover', function( event ) {
customCallback(someAction); // will output your console.log from someAction function (undefined) and customCallback function console.log
customCallback(someAction('hi')); // will output your console.log from someAction function ("hi") and customCallback function console.log
});
google.maps.event.addDomListener( div, 'mouseout', function( event ) {
customCallback(function(event) {
console.log('Do something awesome.');
event.preventDefault();
}); // will output your console.log from someAction function (undefined) and customCallback function console.log
});https://stackoverflow.com/questions/34856720
复制相似问题