不同事件侦听器中的可变accessiblity

时间:2012-03-01 07:33:57

标签: javascript javascript-events

我有三个javascript事件 - mouseup,mousedown和mousemove。在每个事件上调用不同的函数。我希望这三个函数共享一个相同的变量,该变量被赋予这些函数的初始值。
可以这样做吗?
sarfraz要求代码,这里是:

if(window.addEventListener) {
window.addEventListener('load', function () {
  var canvas, context;

  // Initialization sequence.
  var z=false;
  function init () {
    // Find the canvas element.
    canvas = document.getElementById('imageView');
    if (!canvas) {
      alert('Error: I cannot find the canvas element!');
      return;
    }

    if (!canvas.getContext) {
      alert('Error: no canvas.getContext!');
      return;
    }

    // Get the 2D canvas context.
    context = canvas.getContext('2d');
    if (!context) {
      alert('Error: failed to getContext!');
      return;
    }

    // Attach the mousemove event handler.
    canvas.addEventListener('mousedown',ev_mousedown,false);
    canvas.addEventListener('mouseup',ev_mouseup,false);
    canvas.addEventListener('mousemove', ev_mousemove, false);

  }
  //The mouseup

  function ev_mouseup(ev)
  {
   z=false;
  }
  //The mousedown
  function ev_mousedown(ev)
  {
   z=true;
  }
  // The mousemove event handler.
  var started = false;
  function ev_mousemove (ev) {
    var x, y;

    // Get the mouse position relative to the canvas element.
    if (ev.layerX || ev.layerX == 0) { // Firefox
      x = ev.layerX;
      y = ev.layerY;
    } else if (ev.offsetX || ev.offsetX == 0) { // Opera
      x = ev.offsetX;
      y = ev.offsetY;
    }

    // The event handler works like a drawing pencil which tracks the mouse 
    // movements. We start drawing a path made up of lines.
    if (!started) {
      if(z){
      context.beginPath();
      context.moveTo(x, y);
      started = true;
      }
    } else {
      context.lineTo(x, y);
      context.stroke();
    }
  }

  init();
}, false); }

3 个答案:

答案 0 :(得分:2)

使用:

  • 全球
  • 围绕变量和事件处理程序的闭包

答案 1 :(得分:2)

就像昆汀所说,你可以尝试像

这样的东西
//Create a global object
//Best practice is to use a single global namespace
//Prevents pollution of your variables
var myNamespace = {myKey: 'some initial value'};
$('#id').mouseup(do something with myNamespace)
$('#id').mousedown (do something with myNamespace)
$('#id').mousemove(do something with myNamespace)

答案 2 :(得分:1)

你可以使用全局变量,除非在事件函数中声明了相同的变量名,否则它将覆盖全局变量;

var test; //global var

$().mouseup(function(){
      test='mouseup';
    })
   .mousedown(function(){
      test = 'mousedown';
    })
   .mousemove(function(){
      var test; //overwrite global variable
      test = 'mousemove';

      //in this case global test keeps the previous value
      //while local test has 'mousemove' value

    });
相关问题