扩展 jQuery 核心的用处
我发现了一种扩展核心 jQuery init 函数的方法(每当您使用 $() 或 jQuery() 函数时都会调用该函数)。使用普通代理模式是不可能的,但以下代码可以使其工作:
var origInit = jQuery.fn.init;
jQuery.fn.init = function(selector, context, rootjQuery) {
if (some condition) {
//custom code here, possibly returning some other jQuery object than
//what jQuery would normally return
}
return origInit.call(jQuery.fn, selector, context, rootjQuery);
}
我的问题是这可能有用,因为我意识到使用它来缓存选择器的最初意图是有问题的(因为它会影响其他选择器的行为)插件——我最终使用了一个单独的函数来进行缓存)。
所以我想我应该分享这个方法,并且我也很想听到关于它的潜在用途的其他想法。我想也许它可以用来支持某种类型的自定义选择器,尽管我不确定何时需要它,因为 jQuery 已经提供了很多选择器。
I discovered a method of extending the core jQuery init function (which is what gets called anytime you use the $() or jQuery() function). This is not possible using the ordinary proxy pattern but the following code makes it work:
var origInit = jQuery.fn.init;
jQuery.fn.init = function(selector, context, rootjQuery) {
if (some condition) {
//custom code here, possibly returning some other jQuery object than
//what jQuery would normally return
}
return origInit.call(jQuery.fn, selector, context, rootjQuery);
}
My question is where this might be useful, since I realized my initial intent of using it for caching of selectors was problematic (since it would affect the behavior of other plugins -- I ended up using a separate function for caching).
So I thought I'd share the method and I'm also curious to hear other ideas for potential uses of it. I thought maybe it could be used to support custom selectors of some kind, although I'm not sure when exactly that would be needed since jQuery already offers a lot of selectors.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您会发现 jQuery 有一个围绕这个概念构建的方法。
jQuery.sub()
这允许您在本地扩展 jQuery,而无需“破坏”或“改变”全局 jQuery 对象。
根据个人实验,我发现 jQuery 太复杂,无法在不处理各种令人讨厌的边缘情况的情况下更改 init 函数。围绕 jQuery 对象创建工厂装饰方法要好得多。
更改 jQuery 方法或构造函数有很多用途,从日志记录到注入自定义逻辑(例如将 GUID 写入 jQuery 对象)。
You will find that jQuery has a method build around this concept.
jQuery.sub()
This allows you to extend jQuery locally without "corrupting" or "altering" the global jQuery object.
From personal experimentation I find that jQuery is too complex to alter the
init
function without dealing with all kinds of nasty edge cases. It's far better to create a factory decoration method around the jQuery object.There are many uses for changing jQuery methods or the constructor ranging from logging to injecting custom logic like writing a GUID onto jQuery objects.