是否有必要在我的指令中包含一个 destroy 方法 [英] is it necessary to include a destroy method in my directive

查看:29
本文介绍了是否有必要在我的指令中包含一个 destroy 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个非常简单的指令,用于在单击元素时在元素上添加/删除 css 类.

I've written a pretty simple directive that adds/removes a css class on an element when the element is clicked.

app.directive('dropdown', function() {
    var open = false, element,

    callback = function(){
        open = !open;
        if (open) {
            element.addClass('open');
        } else {
            element.removeClass('open');
        }
    };

    return {
        scope: {},
        link: function(scope, elem){
            element = elem;
            elem.bind('click', callback);
            scope.$on('$destroy', function(){
                elem.unbind('click', callback);
                elem.remove();
            });
        }
    };
});

我认为 $destroy 方法可能是不必要的.由于我使用了内置的 jqlite,因此侦听器将与元素一起被销毁,对吗?调用 elem.remove() 也有什么好处.我在一些例子中看到过,但不确定我是否认为有必要.

I think that the $destroy method is probably unnecessary. Since I've used the built in jqlite the listener will be destroyed along with the element right? Also is there any benefit to calling elem.remove(). I've seen it in some examples but not sure if I see the need.

任何想法表示赞赏

C

推荐答案

您肯定不必手动删除元素.您也不需要从作用域中解除任何绑定,因为它将由 angularjs itsef 处理.

You don't have to remove the element manually for sure. You also don't need to unbind anything from scope because it will be handled by angularjs itsef.

对于 jquery dom 侦听器:

For jquery dom listeners:

如果您正在引用 JQuery,那么 angular 将使用它而不是他的内部 jqLit​​e 实现.这意味着将使用原生 jquery remove 方法进行元素删除.删除的 jquery 文档说:

In case you are referencing JQuery then angular will use it instead of his internal jqLite implementation. It means that the native jquery remove method will be used for the element removal. And the jquery documentation for remove says:

与 .empty() 类似,.remove() 方法从DOM.当您想删除元素本身时也使用 .remove()作为里面的一切.除了元素本身,所有绑定事件和与元素关联的 jQuery 数据被删除.

Similar to .empty(), the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

所以我认为你不需要解开你的听众.

So i think that you don't need to unbind your listeners.

但我不是 100% 确定这一点:)

But I'm not 100% sure about this:)

这篇关于是否有必要在我的指令中包含一个 destroy 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆