如何从 knockout 中获取动态生成的 UI 元素

How to get dynamically generated UI Elements from knockout

鉴于以下情况:

<div id="dashboardViewer" data-bind="foreach: dashboards">
    <div data-bind="foreach: widgets">
        <canvas></canvas>
    </div>
</div>

如何访问 canvas 以便在循环浏览小部件时将其传递给 chart.js?似乎我无法为其分配一个 ID 并使用 jquery 或 DOM 实用程序将其拉出,因为它是动态的而不是在 DOM.

要访问该元素,您应该创建一个 custom binding

像这样:

ko.bindingHandlers.chartJS = {
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // This will be called once when the binding is first applied to an element,
        // and again whenever any observables/computeds that are accessed change
        // Update the DOM element based on the supplied values here.

        var data = ko.unwrap(valueAccessor());

        // do stuff with the data, the element and any external libraries such as ChartJS here!
    }
};

你的 HTML 看起来像这样:

<div id="dashboardViewer" data-bind="foreach: dashboards">
    <div data-bind="foreach: widgets">
        <canvas data-bind="chartJS: $data"></canvas>
    </div>
</div>

假设小部件中有您在使用 ChartJS 时需要的一些数据。这就是为什么我将它作为参数传递给绑定处理程序的原因。