Reputation: 1925
I'm using this class in javascript:
function rMotoristaList() {
}
rMotoristaList.prototype.permInsert = false;
rMotoristaList.prototype.permSelect = false;
rMotoristaList.prototype.permUpdate = false;
rMotoristaList.prototype.permDelete = false;
rMotoristaList.prototype.init = function() {
// Pega as permissoes
var perm = new cPermissao();
this.permInsert = perm.verificaPermissao(ID_CAD_MOTORISTAS, "insert");
this.permUpdate = perm.verificaPermissao(ID_CAD_MOTORISTAS, "update");
this.permDelete = perm.verificaPermissao(ID_CAD_MOTORISTAS, "delete");
if (this.permInsert == false) {
$("#btn-add-novo").hide();
}
};
rMotoristaList.prototype.renderGrid = function(data) {
var html = "";
// Faz o loop em todos os elementos retornados
$.each(data,function(index, motorista) {
if (this.permUpdate != false) {
//Do something
}
}
};
The attrbitue permUpdate
is false
, but, when i compare him, inside of $.each(), don't work, i receive a undefined
.
How can i get the value of this.permUpdate
inside $.each()
?
Upvotes: 0
Views: 1233
Reputation:
Inside an anonymous function this
will not refer rMotoristaList
. You can cache this
and use it.
rMotoristaList.prototype.renderGrid = function(data) {
var html = "",
self = this;
// Faz o loop em todos os elementos retornados
$.each(data,function(index, motorista) {
if (self.permUpdate != false) {
//Do something
}
};
Upvotes: 2
Reputation: 4067
There is also another approach, which might be somewhat better in situation like this...
rMotoristaList.prototype.renderGrid = function(data) {
var html = "";
// Faz o loop em todos os elementos retornados
$.each(data,function(index, motorista) {
if (this.permUpdate != false) {
//Do something
}
}.bind(this)); // <-- Bind the function to the right context.
};
This way you are effectively saying, that this function should be executed with the context of rMotoristaList instance.
Upvotes: 1
Reputation: 7466
The this
inside $.each()
refers to the function context of the .each()
and not the one in your code. What you can do is save your context outside of the .each()
block, in JavaScript it's called a Closure, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures.
rMotoristaList.prototype.renderGrid = function(data) {
var html = "";
var that = this;
// Faz o loop em todos os elementos retornados
$.each(data,function(index, motorista) {
if (that.permUpdate != false) {
//Do something
}
}
} ;
Upvotes: 1