我为Flatpickr小部件为Knockout编写了一个自定义bindingHandler。问题是当它被摧毁时它会泄漏内存。堆中填充了分离的DOM树条目。
明显的嫌疑人是“ko.utils.domNodeDisposal.addDisposeCallback”函数调用。我已经将一个console.log添加到dispose回调中,并且控制台正在打印它,因此回调肯定会被触发。我还能做些什么来防止这种内存泄漏?
有问题的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());
}
};