【问题标题】:Run external function when knockout component is created创建淘汰组件时运行外部函数
【发布时间】:2018-10-15 14:42:39
【问题描述】:

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

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/

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

你有这方面的经验吗?你知道如何正确处理吗?

【问题讨论】:

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


    【解决方案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 以使用淘汰组件。

    【讨论】:

    • 太棒了!但是如果我已经有一个包含所有类别的视图模型(因此我将属性实例共享同一个模型)并且我只想用一些视觉效果展示它们呢?我还应该使用'createViewModel(..)'函数吗?假设我在视图模型中已经有这样的东西: categories = ko.observableArray([new Category("Category 1"), new Category("Category 2")]) 我只想将类别的名称显示为HTML 中的无序列表。
    猜你喜欢
    • 2017-04-17
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 2013-02-12
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多