2010-11-09 84 views
3

我在瀏覽html5畫布示例時遇到了此代碼。 我已經粘貼了代碼,並且在我有疑問的地方發表了評論。請解釋此代碼片段

if(window.addEventListener) { 

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

    function init() { 
    canvas = document.getElementById('imageView'); 
    if (!canvas) { 
     alert('Error: I cannot find the canvas element!'); 
     return; 
    } 

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

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

     tool = new tool_pencil(); 

    canvas.addEventListener('mousedown', ev_canvas, false); 
    canvas.addEventListener('mousemove', ev_canvas, false); 
    canvas.addEventListener('mouseup', ev_canvas, false); 
    } 

    function tool_pencil() { 
    var tool = this; 
    this.started = false; 


    this.mousedown = function (ev) { 
     context.beginPath(); 
     context.moveTo(ev._x, ev._y); 
     tool.started = true; 
    }; 

     this.mousemove = function (ev) { 
     if (tool.started) { 
     context.lineTo(ev._x, ev._y); 
     context.stroke(); 
     } 
    }; 

     this.mouseup = function (ev) { 
     if (tool.started) { 
     tool.mousemove(ev); 
     tool.started = false; 
     } 
    }; 
    } 

    function ev_canvas (ev) { 
    if (ev.layerX || ev.layerX == 0) { 
     ev._x = ev.layerX; 
     ev._y = ev.layerY; 
    } else if (ev.offsetX || ev.offsetX == 0) { 
     ev._x = ev.offsetX; 
     ev._y = ev.offsetY; 
    } 

    //Please explain the follwing set of line 
    var func = tool[ev.type]; 
    if (func) { 
     func(ev); 
    } 
    } 

    init(); 

}, false); } 

回答

3

結合其他答案,它正在做的是將所有的回調放在一個對象中。結果是functool.onmousedown,tool.onmouseup

1
//Please explain the follwing set of line 
var func = tool[ev.type]; // Set func to the tool object's member 
          // named 'event.type' 
          // Will set func to undefined if no function is 
          // found in the tool object 
if (func) { // if a func was found then call it. 
    func(ev); 
} 

注意,tool哈希對象被用來保存函數引用,而不是標量,如1,「串」等的Javascript的一個特點是,你可以創建,保存,通運行時功能。

加入謝謝@Chris Morgan指出an_obj ['unknown_key'] ==未定義,不爲空。

另請注意,foo ['a_key']是運行方式foo.a_key - 對象'foo'的'a_key'成員。

最後,Javascript沒有散列。它具有與其他語言中發現的哈希類型相當好的對象。

增加了一些(查看所有的代碼,而不僅僅是有問題的部分)。該代碼正在創建一個對象tool。它有一些成員:

  • started標誌
  • mousedownmouseupmousemove功能

的代碼片段試圖找到相匹配的事件的類型的功能。所以在這種情況下,對象tool被用作對象,而不是散列。我已經更新了答案的第一部分。

+1

如果沒有定義,func將是'undefined',而不是'null'。 – 2010-11-09 05:11:38

0

看起來它試圖將ev.type類型的「工具」分配給變量func。這應該是一個功能。然後它檢查函數是否存在(即是否分配),如果是,則將其作爲參數傳遞參數ev