You can use a coffee script that has a bold arrow (used for the onclick function) to deal with similar things and compiles into well-formed javascript. Using the fat arrow, the coffee script provides the same scope as the function defined in the callback function.
play with the code here
Coffee Script
someObj = () ->
@someMethod1 = () ->
elementBtn = document.getElementById 'myBtn'
elementBtn.onclick = () =>
@someMethod2()
this.someMethod2 = () ->
alert 'OK'
Javascript
var someObj;
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
someObj = function() {
this.someMethod1 = function() {
var elementBtn;
elementBtn = document.getElementById('myBtn');
return elementBtn.onclick = __bind(function() {
return this.someMethod2();
}, this);
};
return this.someMethod2 = function() {
return alert('OK');
};
};
source
share