javascript - 在 EmberJS 模板上使用 DataTables

标签 javascript ember.js datatable document-ready

我正在尝试使用 Datatables在我的 EmberJS 应用程序中。

在常规 jQuery 项目中,我总是使用文档就绪事件并触发其中的 .datatables(); 调用。

$(document).ready(function() {
    $('.has-datatable').dataTable();
});

显然这种方法在 Ember 应用程序中不起作用。


经过一些互联网搜索,我发现这个解决方案乍一看似乎有效:

MyEmberApp = Ember.Application.create();

// This would basically run `dataTable();` after
// every view/template rendering.
Ember.View.reopen({
  didInsertElement : function(){
    this._super();
    Ember.run.scheduleOnce('afterRender', this, this.afterRenderEvent);
  },
  afterRenderEvent : function(){
    $('.has-datatable').dataTable();
  }
});

这有效,数据表插件针对我的 .hbs 模板中定义的表运行,但某些行/单元格是空的,在控制台中我看到:

Uncaught Error: Cannot perform operations on a Metamorph that is not in the DOM.

如果我禁用此修复并运行模板,我会看到普通的旧表正确填充了我需要的所有数据。

我怎样才能实现我的目标?我只需要在 View 渲染(或类似文档的触发器)上保证运行 $('.has-datatable').dataTable();

最佳答案

您可能应该将其包装在 Component 中。此示例不适用于 DataTables,因为我没有使用它,但我将此方法与 jScrollPanejQuery UI Accordion 一起使用(并且也将其用于 Bootstrap Accordion )。基本方法是这样的:

app/components/jqueryui-accordion.js (如果您不使用 ember-cli,您可能必须使用不同的位置和/或略有不同的语法,请参阅下面链接的食谱页面)。

import Ember from 'ember';

export default Ember.Component.extend( {
  classNames: 'has-datatable',

  _enableAccordion: function () {
    this.$().accordion({
      animate: 200,
      heightStyle: 'fill',
      icons: false,
    });
  }.on( 'didInsertElement' ),

  _removeAccordion: function () {
    this.$().accordion('destroy');
  }.on( 'willDestroyElement' )
});

app/templates/components/jqueryui-accordion.hbs

{{yield}}

在您的页面中使用它,例如app/templates/example.hbs

{{#jqueryui-accordion}}
<span>Content the component displays or works with goes here, inserted where the {{yield}} is</span>
{{/jqueryui-accordion}}

http://emberjs.com/guides/cookbook/helpers_and_components/ 使用相同的基本原理(这些示例没有 ember-cli)。

您使用的 afterRender 事件对我来说是新的,但可能也是需要的,当然可以与我的示例结合使用(我不想用新代码破坏它) .

但是,您正在将解决方案应用于每个 View ,这可能是您遇到的问题的一部分:如果存在嵌套的class=,父 View 也会在选择器上触发那里有“has-datatable”

关于javascript - 在 EmberJS 模板上使用 DataTables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25393287/

相关文章:

javascript - app/utils 中用于 ember-cli 应用程序的单元测试模块

ember.js - 刷新 Ember.CollectionView 的 contentBinding 重新排序

java - PrimeFaces 5.1 filterFunction - 是否可以从表中获取整行?

javascript - React 从 url 中提取参数

javascript - javascript 自定义按钮中的确认框

javascript - 天气信息

javascript - DataTables循环遍历表并删除特定列中包含特定字符串的所有行

javascript - 将 Spotify Web Playback SDK 与 React 结合使用

javascript - Ember-cli 如何添加 FileSaverjs 和 Blobjs

javascript - 在静态网站中将数据加载到 JavaScript 中以供立即使用的最快方法是什么?