2011-04-05 4 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을 수정합니다.

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

안녕 : 또한 내가 인스턴스에서 사용할 수 imageLoaded라는 이벤트를 발생주의

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

을 :

은 당신이 이렇게 될 것입니다했다로는 곧 작업해야합니다 , 정말 고맙습니다. 이제 각 이미지의 이미지 속성을 설정할 수있는 다른 클래스 안에 imageProperties가 있습니다. 이것은 앞으로 큰 진보입니다. 이러한 속성을 다른 메서드에서 사용할 수 있도록하는 솔루션이 있습니까? 예 : setImageDimensions (imageProperties) 메서드에서? –

+0

예. http://jsfiddle.net/dimitar/v38Ee/는 imgProperties 클래스를 다른 클래스의 ** mixin **으로 사용하는 방법을 보여줍니다. 추신. 당신도 대답을 받아 들일 수 있습니다 :) 당신이 여러 개의 이미지를 다루는 경우, 마지막 이미지를 가리키는 것이 부적절 할 것입니다. this.images 배열을 고려해 보거나, mootools-more의'Asset.image (s)'와'onload' 이벤트를 사용하여 데이터를 lazyload하십시오. –