Search code examples
javascripthtml5-canvaskineticjs

one function for multiple elements


i am currently drawing elements on the canvas:

  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);

and changing the color of these elements when clicked or touch, but i will have alot of elements on the screen and do not want the same amount of function to change each one.

is there a way to lets say combine the two below to be one function but effect the two above.

  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();
  });

Solution

  • You can extract a common function, and use it like bellow

     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));