Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using ResizeObserver to implement ResizeSensor for the latest modern browsers. #309

Open
fengdh opened this issue Nov 6, 2020 · 1 comment

Comments

@fengdh
Copy link

fengdh commented Nov 6, 2020

ResizeObserver is available for the latest modern browsers for a while. Instead of inserting tricky DIV to catch "resize" event, it is better to simply use ResizeObserver.

image

For backward compability, I rewrite ResizeSensor with ResizeObserver (and Map) as an AMD module below. It works well for my project.

define(function() {
    const observing = new Map(),
          ro = new ResizeObserver(entries => {
                    for (let {target} of entries) {
                        (observing.get(target) || []).forEach(({callback}) => callback(target));
                    }
                });

    function ResizeSensor(elm, callback) {
        observing.set(elm, [...observing.get(elm) || [], {callback, sensor: this]);
        ro.observe(this.elm = elm);
    }

    ResizeSensor.prototype = {
        constructor: ResizeSensor,
        detach() {
            let elm = this.elm;
            ro.unobserve(elm);
            observing.set(elm, [...observing.get(elm) || []].filter(({sensor}) => sensor !== this));
        }
    }

    return ResizeSensor;
});
@Aymkdn
Copy link

Aymkdn commented Dec 4, 2020

Thanks for sharing!

You missed a }, and also I rewrote it to be used with import ResizeSensor from './ResizeSensor.js' in my Webpack project:

const observing = new Map(), ro = new ResizeObserver(entries => {
  for (let { target } of entries) {
    (observing.get(target) || []).forEach(({
      callback
    }) => callback(target));
  }
});

function ResizeSensor(elm, callback) {
  observing.set(elm, [...observing.get(elm) || [], {
    callback,
    sensor: this
  }]); // the missing '}' was there
  ro.observe(this.elm = elm);
}

ResizeSensor.prototype = {
  constructor: ResizeSensor,
  detach() {
    let elm = this.elm;
    ro.unobserve(elm);
    observing.set(elm, [...observing.get(elm) || []].filter(({
      sensor
    }) => sensor !== this));
  }
}

export default ResizeSensor;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants