javascript: keyboard, mouse handling mit callbacks



  • hi, ich hab ein simulation object und moechte das keyboard mouse handling in control object auslagern. im moment verwende ich ein paar callback functions. wie kann ich den code etwas schoener designen? ich muss im control ein paar funktionen von simulation aufrufen!

    var simulation = {
      init: function() {
        this.outputcanvas = document.getElementById("myCanvas");
        this.control = new control(this.outputcanvas, this.getResratio, this.test1, this.test2);
    
        this.initCanvas();
        this.createEventListeners();
      },
    
      initCanvas: function() {
        this.outputcanvas.width = this.outputcanvas.scrollWidth;
        this.outputcanvas.height = this.outputcanvas.scrollHeight;
      },
    
      createEventListeners: function() {
        this.outputcanvas.addEventListener('mousemove', this.control.onmove.bind(this.control, event), false);
      },
    
      getResratio: function() {
        return 1;
      },
    
      getOutputcanvas: function() {
        return this.outputcanvas;
      },
    
      test1: function() {
        console.log("inside bounding box");
      },
    
      test2: function() {
        console.log("outside bounding box");
      }
    };
    
    function control(outputCanvas, resRatioCallback, callback1, callback2) {
      var _this = this;
      _this.outputcanvas = null;
      _this.resRatioCallback = null;
      _this.callback1 = null;
      _this.callback2 = null;
    
      var init = function() {
        _this.outputcanvas = outputCanvas;
        _this.resRatioCallback = resRatioCallback;
        _this.callback1 = callback1;
        _this.callback2 = callback2;
      }
    
      this.onmove = function(evt) {
        var mousePos = getMousePos(_this.outputcanvas, event, _this.resRatioCallback());
    
        if (isMouseInArea(mousePos.x, mousePos.y, 10, 10, 10, 10)) {
          // call simulation function
          _this.callback1();
        } else {
          // call simulation function
          _this.callback2();
        }
      }
    
      init();
    }
    
    $(document).ready(function() {
      simulation.init();
    });
    
    function getMousePos(canvas, evt, resratio) {
      var rect = canvas.getBoundingClientRect();
      return {
        x: (evt.clientX - rect.left) * resratio,
        y: (evt.clientY - rect.top) * resratio
      };
    }
    
    function isMouseInArea(mouseX, mouseY, boundingBoxX, boundingBoxY, boundingBoxW, boundingBoxH) {
      if (mouseX >= (boundingBoxX - boundingBoxW / 2) && mouseX < (boundingBoxX + boundingBoxW * 2) &&
        mouseY >= (boundingBoxY - boundingBoxH / 2) && mouseY < (boundingBoxY + boundingBoxH * 2)) {
        return true;
      }
    
      return false;
    }
    

    test: https://jsfiddle.net/kg97pd32/3/


Log in to reply