是否有任何不引人注目的方式来挂钩触发器的jQuery方法? [英] Is there any unobtrusive way to hook into jQuery methods for triggers?

查看:83
本文介绍了是否有任何不引人注目的方式来挂钩触发器的jQuery方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何不引人注目的方法来挂钩attr,data,css等方法并调用自定义触发器?

I was wondering if there was any unobtrusive way to hook into methods such as attr, data, css, etc and call custom triggers?

理想情况下,我可以做类似这样的事情:

Ideally, I could do something like this:

$(".friend a").bind("attr.changed", changed /* data */, function(e) {
    alert("The " + changed.attribute + " attribute changed from " + changed.from + " to " + changed.to + "!");
});

$(".friend").append(
  $("<a/>").
    attr("href", "#").
    html("Friend 1").
    click(function() { alert('I was clicked!'); }); // creates the element, doesn't execute since element didn't exist

$(".friends a").each(function() {
  var $this = $(this);
  $this.attr("rel", "friend"); // triggers "attr.changed"
});

理想情况下这是将能够在任何元素上触发并将attr更改,从一个对象传递到每个jQuery方法内部的触发器调用。

Ideally this would be able to be triggered on any element and pass the attr changed, from and to in an object to the trigger call from inside each jQuery method.

推荐答案

写一个钩子函数很容易:

It's pretty easy to write a "hook" function:

function hook(original, wrapper) {
    return function() {
        wrapper.apply(this, arguments);
        return original.apply(this, arguments);
    }
}

您提供的包装器函数将使用相同的a调用在原始函数本身被调用之前,作为原始函数的参数。

The wrapper function you provide will be called with the same arguments as the original function, before the original function itself is called.

使用示例:

$.fn.attr = hook($.fn.attr, function(attribute, value) {
    alert('attribute: '+attribute+', value: '+value);
});
$('a.pie').attr('href', 'http://blueberry.pie');
// An alert says "attribute: href, value: http://blueberry.pie"

(旁注:让你的包装取消对原始函数的调用是一个简单的扩展,同样,但这比你想要的更有特色。)

(Sidenote: It'd be an easy extension to let your wrapper cancel the call to the original function, as well, but that's getting more featureful than you wanted.)

你可以直接用它做你想做的事,或者你可以做 wrapper 函数只需触发您以标准jquery方式监听的自定义jquery事件。

You could either use this directly to do what you want, or you could make the wrapper function just fire custom jquery events which you listen for in the standard jquery ways.

这篇关于是否有任何不引人注目的方式来挂钩触发器的jQuery方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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