I'm writing a knockout component, and I need to do some manipulation of the DOM objects within the component via jquery.
How do I get a reference to an element? I can't put an id
attribute on it because it'll be repeated for each instance of the component on the page.
Consider this example:
<!-- 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;
});
How can I grab a jquery reference to the audio tag, when there will be more than one instance of the component on the page?
If you register your component with a createViewModel
factory function you have access to the relevant DOM parts upon instantiating a component.
From the docs , see the comments about 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: ...
});
I'd strongly suggest to do the DOM manipulation via knockout and its data-binds though.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.