我创建了一个 plunkr demo的问题。我在这里面临的问题非常简单:手动调用 $destroy 或删除元素不会触发 $destroy 事件。
function link(scope, element, attrs) {
// call scope $destroy, However it doesn't fire the event
scope.$destroy();
// This also won't fire $destroy
element.remove()
scope.$on("$destroy", function handleDestroy() {
console.log("I am destroyed")
})
}
看完这个我更糊涂了answer .如果 element
也得到一个 $destroy 事件,那么为什么人们在 scope
$destroy 而不是 element
$destroy 解除绑定(bind)事件?
最佳答案
$destroy
事件的回调还没有在代码中设置;因此,将其移动到调用 scope.$destroy()
所以,它变成了:
function link(scope, element, attrs) {
// this is fired when scope.$destroy() is called
scope.$on("$destroy", function handleDestroy() {
console.log("I am destroyed")
});
//
scope.$destroy();
// this will fire when element.remove() is called
element.on('$destroy', function(){
console.log('elem destroyed');
});
//
element.remove();
}
关于javascript - scope.$destroy 未被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40427651/