它是必要在我的指示一destroy方法 [英] is it necessary to include a destroy method in my directive

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

问题描述

我已经写了pretty简单的指令,增加被点击的元素时在元素上/删除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();
            });
        }
    };
});

我认为$销毁方法可能是不必要的。由于我使用内置的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.

有什么想法AP preciated

Any thoughts appreciated

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然后将角用它来代替他的内部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()时,卸下摆臂()方法取出的元件
  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天全站免登陆