简体   繁体   English

数据表、es6 箭头函数和这个

[英]DataTables, es6 arrow functions and this

I have the following datatables initialisation in which I use the preDrawCallback function to hide and show pagination and filters based on the number of records in the table.我有以下数据表初始化中,我使用preDrawCallback根据表中的记录数函数隐藏和显示分页和过滤器。

As it is part of a webpack project, I have turned it into es6 but I have had to disable the object shorthand for the function as I am unable to find a way of getting the current table without using this :由于它是 webpack 项目的一部分,我已将其转换为 es6,但我不得不禁用该函数的对象简写,因为我无法找到一种不使用this获取当前表的方法:

 $tables.DataTable({ preDrawCallback: function(settings) { // eslint-disable-line object-shorthand const $table = $(this); // is there a way to get this table without using this? // rest of code } })

Having looked through a lot of documentation, there doesn't seem to be an argument they pass into the function where I can get that table and all the examples use $(this) .查看了大量文档后,他们似乎没有将参数传递给我可以获取该表的函数,并且所有示例都使用$(this)

My question is do I have to use this or is there some other way of getting the table so I can change the named function into an arrow function?我的问题是我必须使用这个还是有其他方法来获取表格以便我可以将命名函数更改为箭头函数?

Update更新

Seems that I was looking at the wrong problem and didn't need to use arrow functions after all and fixing the lint error solved the need to not use this (see answer below), but just in case anyone doesn't want to use this , after a lot of console logging of different things, I found the current table id is held in the settings that is passed in so you can do似乎我在看错误的问题,毕竟不需要使用箭头函数,修复 lint 错误解决了不使用this的需要(请参阅下面的答案),但以防万一有人不想使用this , 在对不同的事情进行了很多控制台日志记录之后,我发现当前表 ID 保存在传入的设置中,因此您可以执行

$(`#${settings.sTableId}`).DataTable();

If, as you say, the value isn't passed in as a parameter, then you'll need to use a normal function.如果,如您所说,该值不是作为参数传入的,那么您将需要使用普通函数。 Normal functions and arrow functions have different behaviors for this , so you'll need to pick the right tool for the job.普通函数和箭头函数this有不同的行为,因此您需要为这项工作选择正确的工具。

As for that lint error you're seeing, that doesn't have anything to do with arrow functions.至于你看到的那个 lint 错误,这与箭头函数没有任何关系。 It's just telling you to write it like this:它只是告诉你这样写:

$tables.DataTable({
  preDrawCallback(settings) { // <-- using shorthand on this line
    const $table = $(this); 

    // rest of code
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM