When this
keyword is used in jQuery listener, it refers to the DOM element. Is there a way for it to refer to parent function?
Let's use this simple snippet:
var myApp = {
init: function() {
// `this` refer to myApp
$('.my-button').on('click', this.clickListener);
},
clickListener: function(e) {
e.preventDefault();
// now `this` refer to `.my-button`
// how to make it refer to myApp?
this.printLorem();
},
printLorem: function() {
console.log('lorem ipsum dolor sit');
}
};
myApp.init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button class="my-button">Print Lorem Ipsum</button>
I have been wondering about this for years, so far I simply type in the var name like myApp.printLorem()
instead of this.printLorem()
but there's got to be cleaner way.