我已经为Flatpickr小部件为 Knockout 编写了一个自定义 bindingHandler 。问题是它在被销毁时会泄漏内存。堆中充满了分离的 DOM 树条目。
明显的嫌疑人是“ko.utils.domNodeDisposal.addDisposeCallback”函数调用。我在 dispose 回调中添加了一个 console.log,控制台正在打印它,所以回调肯定会触发。我还能做些什么来防止这种内存泄漏?
有问题的 bindingHandler:
ko.bindingHandlers.flatpickr =
{
init: function(element, valueAccessor)
{
const el = $(element);
const picker = new Flatpickr(element,
{
inline: true,
enableTime: true,
time_24hr: true,
minuteIncrement: 1
}
);
el.data('pickrInstance', picker);
ko.utils.registerEventHandler(element, 'change',
function ()
{
valueAccessor()(moment(picker.selectedDates[0]));
}
);
ko.utils.domNodeDisposal.addDisposeCallback(element,
() =>
{
console.log('destroy');
picker.destroy();
}
);
},
update: function(element, valueAccessor)
{
let value = valueAccessor();
let unwrapped = ko.unwrap(value);
const picker = $(element).data('pickrInstance');
picker.setDate(unwrapped.toDate());
}
};