gpt4 book ai didi

javascript - 在手动触发时绑定(bind)丢失的实例

转载 作者:行者123 更新时间:2023-12-01 00:38:12 25 4
gpt4 key购买 nike

我正在尝试存储在构造函数内声明的 DataTable 实例,这似乎一直有效,直到我手动触发过滤器的 change 事件。事实上,我有一个选择的 #filter 来填充 DataTable 实例,如果我这样做的话:

$('#filter').trigger('change');

我可以看到DataTable实例,但如果我手动更改选择选项,我会得到实例值null

这是我的代码:

function ContactHelper() {
this.init();
this.contactsTable = null;
}

ContactHelper.prototype.init = function() {
console.log('initialized');

$('#filter').on('change', function() {
let newData = {
'first_name': 'foo'
};

console.log(this.contactsTable);;
this.contactsTable.row.add(newData);
}.bind(this));

this.initContactsTable();
};

ContactHelper.prototype.initContactsTable = function() {
this.contactsTable = $('#my-dataTable').DataTable({
columns: [{
data: 'first_name'
}
],
destroy: true,
});

$('#filter').trigger('change');
};

$(document).ready(function() {
let cHelper = new ContactHelper();
});
<link  href="//cdnjs.cloudflare.com/ajax/libs/datatables/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" >
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/datatables/1.10.7/js/jquery.dataTables.min.js"></script>

<table id="my-dataTable" class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<select id="filter">
<option value="0">foo</option>
<option value="1">foo2</option>
</select>

如您所见,我将 this 绑定(bind)到 change 事件,我的代码有问题吗?

fiddle :https://jsfiddle.net/twx0bdfq/

最佳答案

在构造函数中调用 init() 方法后,将 contactsTable 设置为 null。试试这个:

function ContactHelper() {
this.init();
}

ContactHelper.prototype.init = function() {
$('#filter').on('change', function() {
let newData = {
'first_name': 'foo'
};

this.contactsTable.row.add(newData);
}.bind(this));

this.initContactsTable();
};

ContactHelper.prototype.initContactsTable = function() {
this.contactsTable = $('#my-dataTable').DataTable({
columns: [{
data: 'first_name'
}
],
destroy: true,
});

$('#filter').trigger('change');
};

$(document).ready(function() {
let cHelper = new ContactHelper();
});
<link  href="//cdnjs.cloudflare.com/ajax/libs/datatables/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" >
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/datatables/1.10.7/js/jquery.dataTables.min.js"></script>

<table id="my-dataTable" class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<select id="filter">
<option value="0">foo</option>
<option value="1">foo2</option>
</select>

关于javascript - 在手动触发时绑定(bind)丢失的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57925490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com