2011-10-24 85 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; 
     },