2013-03-25 19 views
1

我有一個項目中的以下功能我工作:圖像.onerror調用的範圍中有哪些變量?

var makePreviewSimulationDiv = function(){ 
    var errorFlag = false; 

    imgError = function(image){ 
     errorFlag = true; 
    }; 

    var that = this, proxy = new IAProxy(), 
     //imageSource = real_image_source, 
     imageSource = "", 
     image = that.append('<img class="foo" onerror="imgError(this); 
          "src=' + imageSource + '></img>') 
        .children('.sim-ui-preview-sim-image'), 
     container = image.run(encapsulateImg), 
     iconsDiv = that.append('<div class="bar"></div>') 
         .children('.bar'); 

    if (!errorFlag){ 
     image.load(function(){ 
      container.run(zoomMaxWidth) 
       .run(makeDraggable) 
       .run(makeZoomable); 
     }); 
    } else{ 
     alert('image load error!'); 
    } 

    return that; 
}; 

目前,我有圖片src設置爲""嘗試調試功能的行爲,如果它得到一個不好的形象src或沒有圖像src,以努力使其失敗。目前,我的代碼正確捕捉錯誤並拋出alert('image load error!');。但是,如果我在本地範圍我imgError功能,即代碼更改爲以下:

var imgError = function(image){ 
     errorFlag = true; 
    }; 

imgError可以不再當onerror觸發的圖像加載找到。在onerror中調用的函數的範圍是什麼,可以將imgError移動到它的作用域中,而不會在全局範圍內聲明它,同時仍然可以從imgError內訪問errorFlag

+0

在你的情況,只是圖像本身和窗口。 – 2013-03-25 20:00:04

+0

有沒有一種重構方式,我將.onerror屬性添加到允許我訪問makePreviewSimulationDiv函數的局部變量的圖像中? – ckersch 2013-03-25 20:04:09

+1

是的,用'var img = new Image()'創建圖像,綁定到它的錯誤並加載處理程序,並用'$(img).on(「load」,loadHandler「)設置它的src。on(」error「 ,errorHandler)[0] .src = imageSource'現在,在上述兩個處理程序中,您都可以訪問'this',並且所述處理程序的第一個參數將成爲事件對象。 – 2013-03-25 20:09:52

回答

1

創建

var img = new Image() 

綁定形象,這是錯誤和負載處理程序,並設置其與

$(img).on("load",loadHandler).on("error",errorHandler)[0].src = imageSource; 

SRC內上述兩種處理器的現在,你有機會獲得this和所述處理程序的第一個參數將是event object

function errorHandler(event) { 
    console.log(event); 
} 
function loadHandler(event) { 
    console.log(event); 
    $(this).appendTo("#imgHolder"); 
} 
0

在凱文B的評論的幫助下計算出來。這是我的解決方案:

var makePreviewSimulationDiv = function(){ 
    var errorFlag = false; 

    var that = this, proxy = new IAProxy(), 
     image = that.append('<img class="foo"></img>').children('.foo'), 
     imageSource = ""; //a source that should cause an error 


    var imgError = function(image){ 
     errorFlag = true; 
    }; 

    image.on("error",imgError)[0].src = imageSource 

    var container = image.run(encapsulateImg), 
     iconsDiv = that.append('<div class="bar"></div>').children('.bar'); 

    if (!errorFlag){ 
     image.load(function(){ 
      container.run(zoomMaxWidth) 
       .run(makeDraggable) 
       .run(makeZoomable); 
     }); 
    } else{ 
     alert('image load error!'); 
    } 

    return that; 
}; 
+0

啊,是的,現在我理解這個問題!你追加函數的原始方式,它只會尋找'onerror =「imgError(this)」'< - ** imgError **是一個全局函數/變量,這就是爲什麼它不是'不工作。 – 2013-03-25 20:26:34