如何使用命名空间创建jQuery元素方法 [英] How to create jQuery Element Methods with NameSpace

查看:68
本文介绍了如何使用命名空间创建jQuery元素方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以这么说,我想对我的插件做些分支,然后决定我可以对其进行命名空间".到目前为止,将$.method重写为$.namespace.method很容易.

Suffice it to say, I'm wanting to branch my plugin writing a bit, and decided I want to be able to "namespace" them. So far, rewriting the $.method ones to $.namespace.method has been easy.

我遇到的问题是使用像$('element').method()这样的Element方法,但是要使用命名空间.例如$('element').namespace.method().我已经尝试了几种解决方法并可以创建$.fn.namespace.method,但是,当我从该方法中调用this时,我只会得到$.fn.namespace而不是我想要获得的'element'.

The problem I'm having is making Element Methods such as $('element').method(), but to use a namespace; for example $('element').namespace.method(). I've tried a few workarounds and can create $.fn.namespace.method, however, when I call this from within that method, I only get $.fn.namespace and not the 'element' that I'd like to get.

示例:如果我调用$('body').namespace.test(),则在方法test中,我希望this是元素<body></body>

Example: If i call $('body').namespace.test(), then inside method test, I want this to be the element <body></body>

任何帮助弄清楚如何实现这一目标的人都非常感激.可能只是像往常一样过度思考.

Any help figuring out how to pull this off much appreciated. Probably just over-thinking things as usual.

目前为止,对于$('body').namespace().method()之类的东西,目前正在尝试可能的解决方法,效果不佳...:P

Currently trying possible work-arounds for something like $('body').namespace().method(), thus far, not working so well ... :P

推荐答案

如果不需要与IE8兼容,则可以使用

If you don't need to be compatible with IE8, you may use Object.defineProperty.

工作示例:

 Object.defineProperty($.fn, 'namespace', {
  get: function(){
    var t = this;
    return {
      lowercasehtml: function(){
         return t.html(function(_,h){ return h.toLowerCase() }); 
      }
    }
  }
});

$('#a').namespace.lowercasehtml(); // changes the html of #a to lowercase (yes, it's stupid, I know)

演示

Demonstration

但是我不相信这样的命名空间是个好主意.我会简单地定义

But I'm not convinced it's a good idea to namespace like this. I would have simply defined

$.fn.namespace_lowercasehtml = function() ...

这就是我个人对jQuery的应用程序特定扩展所做的.

That's what I personally do for my application specific extensions to jQuery.

这篇关于如何使用命名空间创建jQuery元素方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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