1

I need to attach a function to the resize event, but it doesn't work if the function has parameters, it works if I execute the function inside an anonymous function, but then I'm not able to remove the listener as theirs no reference to it.

Here is my code:

addEvent(window, 'resize', self.center(e) ); // Doesn't work

addEvent(window, 'resize', function() { // Does work but can't remove the listener
    self.center(e);
});

'addEvent' is just a simple cross-browser event listener function. I don't get any errors, the event just doesn't fire.

No jQuery answers please.

Edit:

addEvent Function:

function addEvent(elem, event, fn) {
    if(elem.addEventListener) {
        elem.addEventListener(event, fn);
    } else {
        elem.attachEvent('on' + event, fn);
    }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
KeironLowe
  • 711
  • 1
  • 8
  • 21
  • But then how can I pass the element through? – KeironLowe Dec 09 '13 at 09:40
  • You want the listener to listen only at certain time ? – Merlin Dec 09 '13 at 09:41
  • can you show where your method `center` is written? is `self` evaluates properly? try by removing self and just use center `addEvent(window, 'resize', center );` event will be passed automatically – muneebShabbir Dec 09 '13 at 09:44
  • What library you're using? `addEvent` is not a native host function to attach events. – Teemu Dec 09 '13 at 09:51
  • @Teemu I'm not using a library, addEvent is a custom function. Please see the edit. – KeironLowe Dec 09 '13 at 09:54
  • @muneebShabbir Let's just say for now that center just alerts 'test'; If I remove the parameter and just use `addEvent(window, "resize", self.center );` it works, but if I add a parameter it doesn't work. – KeironLowe Dec 09 '13 at 09:56
  • OK, the edited post answers my question well. Anyway, `onresize` is a bit problematic, it's triggered several times during the window being resized. I've used a debouncer like [this provided by BGerrissen](http://stackoverflow.com/a/4298672/1169519). – Teemu Dec 09 '13 at 10:02
  • @KeironLowe where is center written? – muneebShabbir Dec 09 '13 at 10:04
  • @KeironLowe I've created a [fiddle](http://jsfiddle.net/LNZby/1/) for you, but it's so hacky, that I'm not sure, if I dare to make it an answer : ). Also you can see it working only in the console, since moving windows by web apps is not usually allowed in browsers. Also for some reason IE8 can't find `event.type`, which is weird, since it was available even in IE5. I've tested the snippet functionality in IE8 with IE11 emulating mode only though. – Teemu Dec 09 '13 at 18:19

0 Answers0