2014-09-22 88 views
1

目前我正在畫在畫布上的元素:一個函數多個元素

var head = new Kinetic.Ellipse({ 
    x: stage.width()/2, 
    y: 100, 
    radius: { 
      x: 50, 
      y: 60 
     }, 
    fill: '#DDDDDD', 
    stroke: 'black', 
    strokeWidth: 2 
    }); 

    var neck = new Kinetic.RegularPolygon({ 
    x: stage.width()/2, 
    y: 180, 
    sides: 4, 
    radius: 70, 
    fill: '#DDDDDD', 
    stroke: 'black', 
    strokeWidth: 2 
    }); 

layer.add(neck); 
layer.add(head); 

,並點擊或觸摸時改變這些元素的顏色,但我會在屏幕上的元素很多,不想相同數量的功能來改變每一個。

有沒有辦法讓我們說下面兩個是一個功能,但影響上述兩個。

head.on('touchstart, mousedown', function() { 
    var current = this.getFill(); 
    var fill = ""; 
    switch (current) { 
     case "#DDDDDD": 
     fill = "#FFC926"; 
     break; 
     case "#FFC926": 
     fill = "#FF0000"; 
     break; 
     case "#FF0000": 
     fill = "#000000"; 
     break; 
     default: 
     fill= "#DDDDDD"; 
    } 
    this.setFill(fill); 
    layer.draw(); 
    }); 

    neck.on('touchstart, mousedown', function() { 
    var current = this.getFill(); 
    var fill = ""; 
    switch (current) { 
     case "#DDDDDD": 
     fill = "#FFC926"; 
     break; 
     case "#FFC926": 
     fill = "#FF0000"; 
     break; 
     case "#FF0000": 
     fill = "#000000"; 
     break; 
     default: 
     fill= "#DDDDDD"; 
    } 
    this.setFill(fill); 
    layer.draw(); 
    }); 

回答

1

您可以提取一個共同的功能,並使用它像波紋管

var evaentListener = function(obj) { 
    return function() { 
     var current = obj.getFill(); 
     var fill = ""; 
     switch (current) { 
      case "#DDDDDD": 
      fill = "#FFC926"; 
      break; 
      case "#FFC926": 
      fill = "#FF0000"; 
      break; 
      case "#FF0000": 
      fill = "#000000"; 
      break; 
      default: 
      fill= "#DDDDDD"; 
     } 
     obj.setFill(fill); 
     layer.draw(); 
    } 
} 

head.on('touchstart, mousedown',evaentListener(this)); 

neck.on('touchstart, mousedown',evaentListener(this)); 
+0

完美謝謝 – odd 2014-09-22 14:36:05