Javascript scope issues
I am extending dojo's dojox.data.JsonRestStore and I want to provide my own fixed scheme. this is getUsername won't work because it doesn't refer to the current datastore Take a look at this code:
/**
* @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");
}
}
}
});
Can you tell me what to replace ??? with?
EDIT: Here's the code that works but it's ugly as hell, can someone tell me how to fix this?/**
* @author user
*/
dojo.provide("cms.user.UserAuthenticationStore");
dojo.require("dojox.data.JsonRestStore");
dojo.declare("c开发者_开发百科ms.user.UserAuthenticationStore", [dojox.data.JsonRestStore], {
schema: {
prototype: {}
},
constructor: function(){
var that = this;
this.schema.prototype.getUsername = function(){
return that.getValue(this, "username");
}
}
});
Instead of:
this.schema.prototype.getUsername = function() {
return ???.getValue(this, "username");
}
You can try:
this.schema.prototype.getUsername = dojo.hitch(this, "getValue", <this>, "username");
where "<this>
" is the variable being used as the first parameter of the getValue function. Otherwise, your "that
" isn't too ugly, but people usually call it "self
" or something.
Edit:
Maybe this will work? Quick and dirty way to create a new schema. Otherwise, you might want to create another component that defines your own scheme separately. Then you can just create a "new MySChema()" as the "schema" var.
dojo.declare("cms.user.UserAuthenticationStore", [dojox.data.JsonRestStore], {
self: this,
schema: new (function() {
this.getUsername = function () { return self.getValue(this, "username"); }
}
})();
});
Here's the right way to do this:
/**
* @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(){
}
});
精彩评论