2012-03-01 2 views
0

나는 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); } 
+0

및 관련 코드는 어디에 있습니까? – Sarfraz

답변

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 

    }); 
2

사용 중 하나

  • 변수 감싸 글로벌
  • 클로저 이벤트 핸들러
2

처럼 ent틴은 다음과 같이 시도 할 수 있다고 말합니다.

//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) 
관련 문제