2011-10-24 83 views
2

我試圖寫一個基於原型模式的jQuery插件。

我的問題是當我使用$.ajax函數加載一個xml文件時,我鬆開了this對象。

例如這項工作:

Plugin.prototype = {   
     defaults: { 
      message: 'Hello world!'    
     }, 
     init: function() {    
      this.setStyleAndOptions(); 
      return this; 
     }, 
     setStyleAndOptions: function() {     
      alert("setStyleAndOptions : "); 
     } 
} 

但是,這並不,我得到一個錯誤說 「this.setStyleAndOptions沒有定義」:

Plugin.prototype = { 

     defaults: { 
      message: 'Hello world!' 
     }, 
     init: function() {    
      $.ajax({ 
       type: "GET", 
       url: "param.xml", 
       dataType: "xml", 
       success: this.initOptions 
      });        
      return this; 
     },   
     initOptions: function(dataxml) {   
      // Error occured here, I suppose "this" is not the plugin anymore 
      this.setStyleAndOptions(); 
     }, 
     setStyleAndOptions: function() {     
      alert("setStyleAndOptions"); 
     } 
} 

感謝您的幫助。

回答

1

的問題是,this是在錯誤的時刻的功能。您可以嘗試使用應用程序或通話功能:

Plugin.prototype = { 

    defaults: { 
     message: 'Hello world!' 
    }, 
    init: function() {    
     $.ajax({ 
      type: "GET", 
      url: "param.xml", 
      dataType: "xml", 
      success: function(){ 
       this.initOptions.apply(this, arguments); 
      } 
     });        
     return this; 
    },   
    initOptions: function(dataxml) { 
     this.setStyleAndOptions(); 
    }, 
    setStyleAndOptions: function() {     
     alert("setStyleAndOptions"); 
    } 
} 
+0

謝謝。這是我剛剛宣佈另一個變量的正確方向,因爲在成功函數中,這是函數。但與第一個答案的混合做到了這一點 – user788721

3

嘗試在一個變量存儲this

 init: function() { 
      var that = this;   
      $.ajax({ 
       type: "GET", 
       url: "param.xml", 
       dataType: "xml", 
       success: that.initOptions 
      });        
      return that; 
     },