给出以下内容:
<div id="dashboardViewer" data-bind="foreach: dashboards">
<div data-bind="foreach: widgets">
<canvas></canvas>
</div>
</div>
我如何访问画布,以便在遍历小部件时将其传递给chart.js?看来我无法为其分配ID,也无法使用jquery或DOM实用程序将其提取出来,因为它是动态的,而不是在DOM中。
答案 0 :(得分:0)
要访问该元素,您应该创建一个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时,小部件中需要一些数据。这就是为什么我将它作为参数传递给绑定处理程序。