创建敲除组件时运行外部功能

时间:2018-10-15 14:42:39

标签: webpack knockout.js webpack-html-loader

我正在尝试在淘汰赛中创建新组件:

ko.components.register("categories", {
    viewModel: {
        instance: MY_VIEW_MODEL
    },
    template: require('html-loader?interpolate!./components/categories.html')
});

和我的 categories.html 中的HTML块:

<div class="panel" data-bind="foreach: categories, afterRender: ${require('../effects.js').fadePanels()}"></div>

effect.js 内:

function fadePanels() {
    $('.panel').velocity('fadeInPanels', {
        stagger: 250,
    })
}

webpack.config.js

    test: /\.html$/,
    loader: 'html-loader',
    options: {
        interpolate: true
    },
    exclude: /node_modules/

但是它根本不起作用。这是浏览器的输出(控制台中没有错误): enter image description here

您对此有任何经验吗?你知道如何正确处理吗?

1 个答案:

答案 0 :(得分:1)

您可以使用createViewmodel工厂方法来运行采用组件元素的函数。该函数接收包含当前element的信息对象。

ko.components.register("category", {
    viewModel: { 
      createViewModel: (params, info) => {
        fadeIn(info.element);
        return { label: "hello world" }
      } 
    },
    template: `<div data-bind="text: label"></div>`
});

const categories = ko.observableArray(["", "", ""]);
const addCat = () => categories.push("");

ko.applyBindings({ categories, addCat  });

function fadeIn(el) {
  el.classList.add("seeThrough");
  setTimeout(
    () => el.classList.add("fadeIn"), 
    200
  );
}
.seeThrough {
  opacity: 0;
  transition: opacity .25s ease-in-out;
}

.fadeIn {
  opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: categories">
  <li data-bind="component: { name: 'category' }"></li>
</ul>

<button data-bind="click: addCat">add</button>

要使用组件和Webpack,您可能想看看我几天前写的this answer。它描述了如何配置webpack使其与敲除组件一起工作。