简体   繁体   English

在内存对象上使用jQuery on()

[英]Utilising jQuery on() with in-memory objects

I am in the process of writing a jQuery plugin for handling Google analytics tracking using html5 data attributes. 我正在编写一个jQuery插件,用于使用html5数据属性处理Google分析跟踪。

The code is very much still in alpha stage but the attached fiddle shows that it does track the individual dom elements and pushes the right results. 代码仍然处于alpha阶段,但附加的小提琴表明它确实跟踪了各个dom元素并推动了正确的结果。 (You'll see all that in the console). (你会在控制台中看到所有这些)。

My only real worry so far is that of memory usage. 到目前为止,我唯一真正担心的是内存使用情况。 At present I am binding individual event handlers to each element and as we all know that can get messy and memory intensive. 目前,我正在为每个元素绑定单个事件处理程序,因为我们都知道可能会变得混乱和内存密集。

Ideally I'd like to store each tracker object in a central location and perform some sort of look-up inside the jQuery on() function to fire the pushToGoogle() with the correct context. 理想情况下,我想将每个跟踪器对象存储在一个中心位置,并在jQuery on()函数内执行某种查找,以使用正确的上下文触发pushToGoogle()

Unfortunately my JavaScript chops can't quite nail it and I can't figure out an effective way to wrap everything in a neat generic fashion. 不幸的是,我的JavaScript排序不能完全指出它,我无法找到一种有效的方式来以一种整洁的通用方式包装所有内容。

Any ideas?? 有任何想法吗??

You can use event bubbling. 您可以使用事件冒泡。

$(document).on('click', 'a.trackEvent', function () { /* do complicated things */ });

So basicly any a.trackEvent element in document (so all your links with class trackEvent) will execute the function when clicked. 所以基本上,文档中的任何a.trackEvent元素(所有与类trackEvent的链接)都会在单击时执行该函数。

The advantage is only one function exists in memory and if you dynamicly create new dom elements they will also be tracked. 优点是内存中只存在一个函数,如果动态创建新的dom元素,它们也会被跟踪。 You just need some addition code to identify the element. 您只需要一些额外的代码来识别元素。

This used to be the live function: http://api.jquery.com/live/ 这曾经是现场功能: http//api.jquery.com/live/

Turns out that the process was actually quite simple and just required some refactoring. 事实证明,这个过程实际上非常简单,只需要进行一些重构。

I have added my code plugin to github here so that anyone following the question can learn from my example code. 我已将我的代码插件添加到github这里,以便任何关注该问题的人都可以从我的示例代码中学习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM