jQuery.data不再适用于窗口? [英] jQuery.data no longer works with window?

查看:90
本文介绍了jQuery.data不再适用于窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近将项目的jQuery文件从 1.4.2 升级到 1.4.4 ,看起来是 1.4.3 我们一直使用的方式 jQuery.data 已停止工作。

I recently upgraded our project's jQuery file from 1.4.2 to 1.4.4 and it appears that as of 1.4.3 the way we have been using jQuery.data has stopped working.

我们有这个代码:

var events = $(window).data('events');

if (events.scroll)
if (!events.scroll.include(handler))
  $(window).scroll(handler);

目的是防止此特定处理程序被多次绑定。

the purpose is to prevent this particular handler from being bound multiple times.

1.4.2 中,这样可以正常工作。在 1.4.4 中,事件未定义。

In 1.4.2, this works fine. In 1.4.4, events is undefined.

function handler() {
  //do something
}

$(document).ready(function(){
  $(window).scroll(handler);
  $('div#test').scroll(handler);

  $(window).data('events') -> undefined
  $('div#test').data('events') -> Object
});

此API有何变化?我应该如何列出窗口的事件

What changed with this API? How should I list events for window?

我已更改第一行:

var events = $(window).data('__events__').events;

看起来有点凌乱,但将事件连接到普通对象的能力令人信服。

a bit messy-looking, but the ability to wire events to plain objects is compelling.

推荐答案

对于窗口,事件类型的jQuery 1.4.3+发生了变化,以避免对象名称冲突(或任何其他普通对象)使用密钥__ events __代替,如下所示:

There was a change in jQuery 1.4.3+ for event types, to avoid object name collisions, for window (or any other plain object) use the key "__events__" instead, like this:

var events = $(window).data('__events__');

相同的 __ events __ 键用于没有 .nodeType 属性窗口没有,所以它在这里被视为普通对象。)

The same __events__ key is used for any objects that don't have a .nodeType property (which window doesn't, so it's treated like a plain object here).

要清楚这是一次有意识的故意改变,它包含在 jQuery 1.4.3发行说明

To be clear that this was a conscious, intentional change, it's included in the jQuery 1.4.3 release notes:


JavaScript对象

对JavaScript对象(或更准确地说,不是DOM节点的任何东西)使用.data()时进行了大量更改。要在JavaScript对象上设置数据时启动,数据将直接设置在对象上 - 而不是进入内部数据对象库。此外,附加到对象的事件将放入新的 __ events __ 属性中,该属性实际上是一个函数。这样做是为了允许事件直接附加到对象,在收集对象时进行垃圾收集,而不是由JSON序列化程序序列化。这些更改应该使jQuery的数据和事件系统在JavaScript对象上更有用。

JavaScript Objects
A number of changes were made to when .data() is used on JavaScript objects (or, more accurately, anything that isn’t a DOM node). To start whenever you set data on a JavaScript object the data is set directly on the object – instead of going into the internal data object store. Additionally events that are attached to objects are put in a new __events__ property that is actually a function. This was done to allow events to be attached directly to an object, be garbage collected when the object is collected, and not be serialized by a JSON serializer. These changes should make jQuery’s data and event systems much more useful on JavaScript objects.

这篇关于jQuery.data不再适用于窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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