在Aurelia中使用jQuery DataTables

问题描述 投票:0回答:2

我需要一些关于使用Aurelia使用jQuery DataTables的建议。基本上我遇到了两个问题。

  1. repeat.for绑定循环完成后,我无法确定初始化它的最佳方法。显然,即使在attached()生命周期被解雇之后,循环仍然有效。
  2. 如果我使用$(myRef).DataTables(data: myArray)方法填充表,并将链接(<a href-route=... click.delegate=...>)插入该表,Aurelia似乎无法识别链接或激活路由器。

问题1:这是我尝试使用Aurelia的绑定来填充表格。 Aurelia正确地制作了表格,我可以等待2-3秒然后加载DataTables,但这不是正确的方法。我没有触发加载DataTables类的确定事件,因为我不知道repeat.for何时完成。

<div class="table-responsive">
  <table ref="tblUserList" class="table table-condensed table-hover table-striped" width="100%">
    <thead>
      <tr>
        <th><span t="Username"></span></th>
        <th><span t="First_name"></span></th>
        <th><span t="Last_name"></span></th>
      </tr>
    </thead>
    <tbody>
      <tr repeat.for="record of records">
        <td><a route-href="route: user; params.bind: {id: record.user_id}" click.delegate="$parent.select(record)">${record.user_username}</a></td>
        <td>${record.p_fname}</td>
        <td>${record.p_lname}</td>
      </tr>
    </tbody>
  </table>
</div>

问题2:这是我尝试使用jQuery方法填充表。 DataTables成功加载表,但Aurelia无法识别链接或触发操作。

$(this.tblUserList).dataTable({
  "paginate": true,
  "pageLength": 10,
  data: this.records,
  columns: [
    { data: 'user_username',
      fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
        $(nTd).html("<a route-href='route: user; params.bind: {id:" + oData.user_id + "}' click.delegate='$parent.select(" + oData.user_id + ")'>" + oData.user_username + "</a>");
      }
    },
    { data: 'p_fname' },
    { data: 'p_lname' }
  ]
});   

任何人都可以帮我解决上述任何一个问题吗?或者......我是以错误的方式接近整个问题吗?使用jQuery方法填充或Aurelia repeat.for绑定循环更好吗?

aurelia
2个回答
1
投票

我知道这是旧的,但万一,如果它可以帮助。在绑定后添加DOM元素时,它们不是aureliazed。你应该使用TemplatingEngine的增强方法:

  1. 导入TemplatingEngine并注入它: import {inject, TemplatingEngine} from 'aurelia-framework'; @inject(TemplatingEngine)
  2. 在构造函数中,初始化模板引擎: constructor(templatingEngine) { this.templatingEngine = templatingEngine; }
  3. 在Aurelia的attached()方法中,执行数据表初始化,并添加一个类以便能够检索新创建的DOM元素: $(nTd).html("<a class='myclass' ...
  4. 增强你的元素: $('.myclass').each(function (index, value) { let el = $(this); if (!el.hasClass('au-target')) { //can't enhance already aureliazed elm this.templatingEngine.enhance({element: el[0], bindingContext: this}); //el[0] is important to have DOM and not jQuery object } });

然后你的绑定应该工作。


1
投票

使用第一种方法(aurelia绑定),从配置对象中删除数据并在activate lifecycle hook中加载数据:

import 'datatables';

export class UserList {
    activate() {
        this.records = [...];
    }

    attached() {
        $(this.tblUserList).dataTable();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.