You can pass your method directly as callback and with .bind
, so run in the scope you need:
class Cliente {
showName(data) {
alert(data.name);
}
getName() {
$.get('/url').done(this.showName.bind(this));
}
}
if you are using a Babel compiler that accepts TC39 proposals you can use Public Class Fields, thus:
class Cliente {
showName = ({name}) => alert(name);
getName() {
$.get('/url').done(this.showName);
}
}
Example of the second working option:
class Cliente {
showName = ({name}) => alert(name);
getName() {
$.get('/url').done(this.showName);
}
}
// estas linhas são só para simular o que `$` faz:
let $ = function() {};
$.prototype.get = function() {return this;};
$.prototype.done = function(fn) {
fn.call(window, {name: 'teste!'});
};
$ = new $();
new Cliente().getName();
About the variable
minha-url
, that is not a valid identifier for theJS
, although I keep this in my answer, I believe you have another name for the variable asminhaUrl
orminha_url
– Gabriel Katakura
yes, it was just to illustrate.
– Felipe Coelho