javascript - 将额外参数传递给 IntersectionObserver?

标签 javascript vue.js vuejs2 vue-component intersection-observer

我如何将额外的参数传递给 IntersectionObserver?我正在尝试为 Vue 创建一个 lazyload 插件。它像这样工作正常,但我也希望能够调用提供的指令函数。

const lazyload = {
    install(Vue) {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach((entry) => {
                if (entry.intersectionRatio > 0) {
                    console.log('In viewport');
                }
            });
        });

        Vue.directive('lazy', {
            inserted(element) {
                observer.observe(element);
            }
        });
    }
};

这意味着在插入的函数中,我会将 binding 设置为第二个参数。

inserted(element, binding)

我如何传递这个绑定(bind),以便我可以在我的 IntersectionObserver 回调中使用它?

最后它应该看起来像这样:

<div class="col-sm-6" v-lazy="fire">

最佳答案

如果您真的想将这些值作为额外参数传递,您可以使用 Function.bind ,但您必须为每个指令调用创建一个单独的 IntersectionObserver。

我会在这里推荐一个 WeakMap,并让回调检查映射以寻找正确的处理程序。像这样的东西:

const lazyload = {
  install(Vue) {
    const handlers = new WeakMap();
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          console.log('In viewport');
          handlers.get(entry.target)();
        }
      });
    });

    Vue.directive('lazy', {
      inserted(element, binding) {
        handlers.set(element, binding.value);
        observer.observe(element);
      }
    });
  }
};

(我没有使用过 Vue,所以我不确定这是否会逐字工作)

顺便说一句,我将 entry.intersectionRatio > 0 更改为 entry.isIntersecting。这可能是一个错误,但我在 Chrome 65 中看到,当滚动速度非常慢时,您可以获得 entry.intersectionRatio === 0 && entry.isIntersecting === true: https://jsfiddle.net/3jgm0ch7/2/

关于javascript - 将额外参数传递给 IntersectionObserver?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48262903/

相关文章:

java - 什么时候不使用 Google Web Toolkit?

javascript - 共享 Angular 2 应用程序,web/mobile-web/Ionic 2

vue.js - 如果在 Vue.js 中禁用输入,则更改背景颜色

javascript - 用于 Angular 应用程序登录/注册的模式/对话框

javascript - 使用 Lodash 重构 Vue 方法?

javascript - 在 vue.js 中引用 v-for 中的先前值

vuejs2 - 使用 @nuxtjs/auth 捕获错误服务器响应

jquery - 如何在 vue.js 中删除类

javascript - 向 JSON 文件 URL 发出 GET 请求并存储响应,以便可以在 Vue.js 应用程序启动时全局使用它?

javascript - 这个意想不到的输出是怎么来的呢?