I have the following Javascript,
eventManager: {
$musicGenres : null, // $musicGenres is the selector for a div-container of inputs
musicGenres : [],
// Functions
handle : function(selectors) {
selectors = (typeof selectors === 'undefined') ? {
'musicGenres' : '#musicGenres'
} : selectors; // selectors default values...
this.$musicGenres = $(selectors['musicGenres']);
console.log("CHANGED $musicGenres TO " + this.$musicGenres);
this.$musicGenres.find('input').change(this.reloadMusicGenres);
},
reloadMusicGenres : function() {
console.log("IN FUNCTION $musicGenres IS " + this.$musicGenres);
},
, call the function eventManager.handle()
on my page and trigger the change-Event of one of those inputs, which outputs
CHANGED $musicGenres TO [object Object]
IN FUNCTION $musicGenres IS undefined
what I don't understand. I've set $musicGenres to a new value, but in the reloadMusicGenres-function it stays undefined. Even when I manually access $musicGenres' value through the console by typing in eventManager.$musicGenres
it outputs the right value.
Could anybody help me? That really worries me.
The
context
ofthis
has changed. The easiest way to address the issue is to referencethis
outside the function, or pass adata
object (as suggested by the two other fine posters, Richard Healy and AlliterativeAlice).A third way is to explicity
bind
the context ofthis
. Using jQuery, you can achieve this by calling$.proxy
. So, this:becomes:
$.proxy
will return a new function, wherethis
will always be bound toeventManager
. If you're interested in moving away from jQuery,Function.prototype.bind
is your answer (Edit: an example of which is provided by Zoltan's answer)Here's some links for documentation on how to use these fine functions:
jQuery proxy: https://api.jquery.com/jQuery.proxy/
Bind function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind