Reputation: 17053
How do I pass in a variable proxy of the "this" context of the Class instance? For example, this.saySomething() isn't doing what I'd like it to.
Do you have any other recommendations on OOJS code organization?
// Truveo Video Player Class
function Player(){
// Player Defaults
this.opts = {
volume: 0 // Initial volume settings
};
}
// Initialize player setup / methods
Player.prototype.init = function(configs){
// Overwrite defaults with custom configs
this.opts = $.extend(this.opts, configs);
$(document).ready(function(){
this.saySomething();
});
$(window).load(function(){
// do something else
});
}
Player.prototype.saySomething = function(){
alert(this.opts.volume);
}
// Create instance for channel surf
var configs = {volume:10};
var cSurf = new Player();
cSurf.init(configs);
Upvotes: 0
Views: 595
Reputation: 322472
In addition to the correct answer from @Box9, one possibility would be to set the value of this
for the entire .ready()
call.
You can do this with the jQuery.proxy()
[docs] method.
$(document).ready( $.proxy(function(){
this.saySomething();
}, this) );
Now in the function that's sent to .ready()
it will have your Player
object as the value of this
.
Upvotes: 1
Reputation: 93664
Save a copy of this
before entering the function:
var me = this;
$(document).ready(function(){
me.saySomething();
});
Upvotes: 3