从淘汰组件中引用DOM元素

BG1*_*100 1 javascript jquery reference custom-component knockout.js

我正在编写一个敲除组件,我需要通过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;
});
Run Code Online (Sandbox Code Playgroud)

当页面上有多个组件实例时,如何获取对音频标签的jquery引用?

use*_*291 5

如果使用createViewModel工厂功能注册组件,则可以在实例化组件时访问相关的DOM部件。

文档中,查看有关以下内容的评论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: ...
});
Run Code Online (Sandbox Code Playgroud)

我强烈建议通过敲除及其数据绑定来进行DOM操作。