我正在编写一个淘汰组件,我需要通过jquery对组件中的DOM对象进行一些操作。
如何获取元素的引用?我无法在其上添加id
属性,因为它将针对页面上每个组件实例重复。
考虑这个例子:
<!-- component template -->
<div>
<p data-bind="text: name">
<audio></audio>
</div>
// View model
define(["jquery", "knockout"], function ($, ko) {
var audioElement = $("????");
function vm(params) {
var self = this;
self.name = params.name;
};
return vm;
});
如果页面上有多个组件实例,我如何获取对音频标签的jquery引用?
答案 0 :(得分:3)
如果使用createViewModel
工厂函数注册组件,则可以在实例化组件时访问相关的DOM部件。
从the docs开始,查看有关componentInfo
的评论:
ko.components.register('my-component', {
viewModel: {
createViewModel: function(params, componentInfo) {
// - 'params' is an object whose key/value pairs are the parameters
// passed from the component binding or custom element
// - 'componentInfo.element' is the element the component is being
// injected into. When createViewModel is called, the template has
// already been injected into this element, but isn't yet bound.
// - 'componentInfo.templateNodes' is an array containing any DOM
// nodes that have been supplied to the component. See below.
// Return the desired view model instance, e.g.:
return new MyViewModel(params);
}
},
template: ...
});
我强烈建议通过敲除和它的数据绑定来进行DOM操作。