0

I have written some namespaced javascript and I'm having trouble binding to window events (such as scroll, resize) and retaining access to my instance of the app, for example:

var app = new function() {

  this.init = function() {
    var self = this;
    window.onresize = self.resize;
  };

  this.resize = function() {
    var self = this;
    console.log(self); // Gives me the window!
  };

};
app.init();

I'd rather not have to declare the function then and there with window.onresize = function()..., because I want to be able to call my app.resize() function independently too. Is there a better way to do this within the scope of my app?

toomanyredirects
  • 1,972
  • 15
  • 23

2 Answers2

2

Niet the Dark Absol's answer is correct and shorter, but learning about call and apply to set the value of this inside functions changed my life! Maybe it will help you too:

window.onresize = function() {

  // calls self.resize() with the value of `this` set to `self`
  self.resize.call(self);

};
Josh Harrison
  • 5,927
  • 1
  • 30
  • 44
  • Redundant - `self.resize()` already uses `self` as the context. – Niet the Dark Absol May 27 '14 at 09:44
  • Yes, I said your answer was correct and shorter. I just remember grappling with the same issue and have found using `.call()` to be the most helpful in some situations. – Josh Harrison May 27 '14 at 09:49
  • Thanks @ZougenMoriver, I've not tried using `call()` or `apply()` yet. I think you're right that @niet-the-dark-absol has the best solution for me in this instance, but thanks for the pointer. – toomanyredirects May 27 '14 at 09:51
1

No reason why you can't do both:

window.onresize = function() {self.resize();};
// calls `self.resize` with the context of `self`
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592