• Using jQuery's datastore vs. expando properties


    http://stackoverflow.com/questions/1160193/using-jquerys-datastore-vs-expando-properties

    Question:

    I'm developing code using jQuery and need to store data associated with certain DOM elements. There are a bunch of other questions about how to store arbitrary data with an html element, but I'm more interested in why I would pick one option over the other.

    Say, for the sake of extremely simplified argument, that I want to store a "lineNumber" property with each row in a table that is "interesting".

    Option 1 would be to just set an expando property on each DOM element (I hope I'm using the term 'expando' correctly):

    $('.interesting-line').each(function(i){this.lineNumber = i;});

    Option 2 would be to use jQuery's data() function to associate a property with the element:

    $('.interesting-line').each(function(i){ $(this).data('lineNumber', i);});

    Ignoring any other shortcomings of my sample code, are there strong reasons why you would choose one means of storing properties over the other?

    Answer:

    Using $.data will protect you from memory leaks.

    In IE, when you assign a javascript object to an expando property on a DOM element, cycles that cross that link are not garbage collected. If your javascript object holds a reference to the dom object, the whole cycle will leak. It's entirely possible to end up with hidden references to DOM objects, due to closures, so you may leak without realizing it.

    The jQuery datastore is set up to prevent these cycles from forming. If you use it, you will not leak memory in this way. Your example will not leak because you are putting primitives (strings) on the DOM element. But if you put a more complex object there, you risk leaking.

    Use $.data so you won't have to worry.

    See also:

    Circular References

    Circular references are the root of nearly every leak. Normally, script engines handle circular references through their garbage collectors, but certain unknowns can prevent their heuristics from working properly. The unknown in the case of IE would be the status of any DOM elements that a portion of script has access to. The basic principle would be as follows:

    http://msdn.microsoft.com/en-us/library/bb250448%28VS.85%29.aspx

  • 相关阅读:
    linux常见的基本操作命令
    CentOS-7安装mongodb
    分布式CAP理论
    Spring-boot2.X整合Apache ActiveMQ5.X
    Apche ActiveMQ5.X介绍及CentOS7的安装
    初识Java消息服务JMS
    初始Apache-Shiro权限认证Web知识点
    Java定时任务总结
    Apache-Shiro自定义Realm实战
    Java 作业题1
  • 原文地址:https://www.cnblogs.com/malaikuangren/p/2892345.html
Copyright © 2020-2023  润新知