2011-04-05 80 views
2
var image; 
var imgProperties = new Class({ 
    image: new Array(), 
    json: function() { 
     var url = protocol + "//" + host + pathname + "/myEchoFile.php"; 
     var jsonRequest = new Request.JSON({ 
      url: url, 
      onSuccess: function(img) { 
       this.image[0] = img.name; 
       this.image[1] = img.width; 
       this.image[2] = img.height; 
       alert('img.name=' + this.name); //alerts myImage.jpg 
      } 
     }).post(); 
     console.log("this.image[0]=" + this.image[0]); //undefined 
     //@fixme 
     //this.image is undefined 
    } 
}); 

回答

3

請求不同步。 (因此它是AJAX)它需要時間來啓動,完成和設置值。

你應該參考你的類的實例從的onSuccess並調用單獨的函數,就像這樣:

var imgProperties = new Class({ 

    Implements: [Events,Options], 

    initialize: function(options) { 
     this.setOptions(options); 
    }, 

    json: function() { 
     new Request.JSON({ 
      url: "//" + host + pathname + "/myEchoFile.php", 
      onSuccess: this.imageLoaded.bind(this) 
     }).post(); 
    }, 
    imageLoaded: function(data) { 
     this.image = [data.name, data.width, data.height]; 
     this.fireEvent("imageLoaded", this.image); 
    } 
}); 

也對onSuccess功能可確保您指向類的實例,而不是注意.bind(this)全局範圍(窗口對象?),這是你之前正在做的事情,修改window.image

把它與匿名的工作,你有這將是這樣的:

onSuccess: function(data) { 
    this.imageLoaded(data); 
}.bind(this) 

也注意到我火叫imageLoaded一個事件,你可以從實例中使用:

new imgProperties({ 
    onImageLoaded: function(imageArray) { 
     // access imageArray 
     // or just access this.image instead! 
     // or export it to your global namespace like before 
     window.image = this.image; 
     // more code that relies on window.image being defined... 
    } 
}).json(); 
+0

喜, 非常感謝。現在我在另一個類中獲得了imageProperties,我可以爲每個圖像設置圖像屬性。這是一大進步。是否有解決方案可以用其他方法提供這些屬性,例如在setImageDimensions(imageProperties)方法中? – 2011-04-06 09:03:37

+0

是的。 http://jsfiddle.net/dimitar/v38Ee/演示如何在另一個類中使用imgProperties類作爲** mixin **。附:你可能也想接受這個答案:)如果你正在處理多個圖像,那麼將這個圖像指向最後一個圖像是不夠的。我會考慮使用this.images數組或更好,使用mootools-more和'onload'事件中的'Asset.image(s)'來延遲加載數據。 – 2011-04-06 09:39:34