wnr / element-resize-detector

Optimized cross-browser resize listener for elements.
MIT License
1.32k stars 118 forks source link

erd.listenTo() always fires initially? #110

Closed pmorch closed 5 years ago

pmorch commented 5 years ago

I was expecting listenTo(elem, func) to fire only when elem gets resized ; when the size changes from its initial size.. But it seems that as soon as one starts listening, an initial call to func is always made, as demonstrated in this codesandbox where we start listening on a div that has long since settled in to a stable state and size, but the callback gets called anyway.

Is this on purpose? Is it guaranteed? If I can rely on that, then I can arrange to discard the very first call to the callback with a if (numCalls++ > 0) thingy. But I'd like to know if there are some corner cases / race coditions (e.g. in some browsers?) where it isn't safe to ignore the initial callback.

I suggest one of these:

  1. Document this behavior, including any gotchas and/or corner cases
  2. Perhaps allow an option to avoid the first, initial call
  3. Acknowledge this as a bug and remove the initial call

I guess 3. isn't going to happen for backwards-compatibility reasons...

If you decide against doing anything for this issue, I'm fine with just closing this issue, but I'm hoping I at least can rely on this behavior or learn the reasoning behind it. I find it odd that the callback gets called immediately in the codesandbox above.

wnr commented 5 years ago

Hi and thanks for the comment. The behavior is per design and guaranteed. I agree that it should be better documented. I'll try and do this ASAP. I think there is an option you can pass to the function named "callOnAdd".

pmorch commented 5 years ago

Thanks!

this.erd = elementResizeDetectorMaker({
    strategy: "scroll", //<- For ultra performance.
    callOnAdd: false,
});

Worked like a charm, exactly as expected.

Ironically, in src/element-resize-detector.js, strategy is not documented, but callOnAdd is, along with several others. As opposed to README.md, where strategy is the only documented option.

So We can cross out 2. from my list. Now only 1. is left... :-) Thanks!

wnr commented 5 years ago

Great! I've documented it now.

pmorch commented 5 years ago

Documented in 2fcd1055641ab6d8fec22b26aaa56bc65b29bb4e