2009-10-08 187 views
1

我在擴展dojo的dojox.data.JsonRestStore,我想提供我自己的固定方案。 這是getUsername不會工作,因爲它並不指當前的數據存儲 看看這個代碼:Javascript範圍問題

/** 
* @author user 
*/ 
dojo.provide("cms.user.UserAuthenticationStore"); 

dojo.require("dojox.data.JsonRestStore"); 

dojo.declare("cms.user.UserAuthenticationStore", [dojox.data.JsonRestStore], { 
    schema: { 
     prototype: { 
      getUsername: function(){ 
       return ???.getValue(this, "username"); 
      } 
     } 
    } 
}); 

你能告訴我是什麼來替代???用?
編輯:
這是可行的代碼,但它是醜陋的地獄,有人可以告訴我如何解決這個問題嗎?

/** 
* @author user 
*/ 
dojo.provide("cms.user.UserAuthenticationStore"); 

dojo.require("dojox.data.JsonRestStore"); 

dojo.declare("cms.user.UserAuthenticationStore", [dojox.data.JsonRestStore], { 
    schema: { 
     prototype: {} 
    }, 
    constructor: function(){ 
     var that = this; 
     this.schema.prototype.getUsername = function(){ 
      return that.getValue(this, "username"); 
     } 
    } 
}); 

回答

0

這裏是這樣做的正確方法:

/** 
* @author user 
*/ 
dojo.provide("cms.user.UserAuthenticationStore"); 

dojo.require("dojox.data.JsonRestStore"); 

dojo.declare("cms.user.UserAuthenticationStore", [dojox.data.JsonRestStore], { 
    schema: { 
     prototype: { 
      store: null, 
      getUsername: function(){ 
       return this.store.getValue(this, "username"); 
      } 
     } 
    }, 
    constructor: function(){ 
     this.schema.prototype.store = this; 
    }, 
    login: function(){ 

    }, 
    logout: function(){ 

    } 
}); 
1

相反的:

this.schema.prototype.getUsername = function() { 
    return ???.getValue(this, "username"); 
} 

你可以試試:

this.schema.prototype.getUsername = dojo.hitch(this, "getValue", <this>, "username"); 

其中 「<this>」 是作爲getValue函數的第一個參數變量之中。否則,你的「that」不是太難看,但人們通常稱它爲「self」或什麼的。

編輯:

也許這會工作嗎?快速和骯髒的方式來創建一個新的模式。否則,您可能需要創建另一個組件來分別定義您自己的方案。然後,您可以創建一個「新的MySChema()」作爲「模式」變種。

dojo.declare("cms.user.UserAuthenticationStore", [dojox.data.JsonRestStore], { 
    self: this, 
    schema: new (function() { 
       this.getUsername = function() { return self.getValue(this, "username"); } 
      } 
    })(); 
}); 
+0

爲什麼我必須這樣做的構造函數? – 2009-10-08 23:58:02

+0

另外這是getUsername imo ... – 2009-10-08 23:58:46

+0

我不遵循getUsername註釋。無論如何,沒有理由在構造函數上做。我甚至不清楚你爲什麼使用scheme.prototype結構。 – Glenn 2009-10-09 00:05:24