是否可以在jQuery中创建命名空间?

时间:2009-02-09 04:01:36

标签: jquery

YUI有一种很好的方法可以在javascript中为你的方法等创建命名空间。

jQuery有类似的东西吗?

8 个答案:

答案 0 :(得分:39)

lpfavreau提供了使用您自己的方法扩展 jQuery对象的解决方案(以便它们的功能适用于实际的jQuery对象上下文)。

如果您想要命名代码,可以使用美元符号,如下所示:

$.myNamespace = { .. };

或“jQuery”:

jQuery.myNamespace = { .. };

请注意您选择的命名空间,因为这可能会覆盖现有的jQuery方法(我建议您首先在jQuery代码中搜索,这样就不会这样做了。)

您可以点击此链接:http://www.zachleat.com/web/2007/08/28/namespacing-outside-of-the-yahoo-namespace/

看看创建自己的函数来复制YUI的作用是多么容易:

// include jQuery first.
jQuery.namespace = function() {
    var a=arguments, o=null, i, j, d;
    for (i=0; i<a.length; i=i+1) {
        d=a[i].split(".");
        o=window;
        for (j=0; j<d.length; j=j+1) {
            o[d[j]]=o[d[j]] || {};
            o=o[d[j]];
        }
    }
    return o;
};

// definition
jQuery.namespace( 'jQuery.debug' );
jQuery.debug.test1 = function()
{
    alert( 'test1 function' );
};
jQuery.debug.test2 = function()
{
    alert( 'test2 function' );
};
// usage
jQuery.debug.test1();
jQuery.debug.test2();

答案 1 :(得分:10)

这就是我为插件创建命名空间的方法:

(function ($) {
    // do not overwrite the namespace, if it already exists
    $.MyNamespace = $.MyNamespace || {};
    $.MyNamespace.MyPlugin = function () {/*here's the logic*/}
})($);

然后:

$.MyNamespace.MyPlugin ();

答案 2 :(得分:5)

jQuery有一堆扩展基本功能的插件。容易命名空间有this plugin

答案 3 :(得分:4)

名称空间插件完全不合格! 世界上最古老的技巧,使用arguments.callee,Function.prototype,然后调用一个新的Function实例,允许您使用$ .fn.extend创建嵌套的命名空间!

这是一个简单明了的例子:

    ;(function($){
    var options= {
        root: function(){ //you don't have to call it 'root', of course :)
            //identify the function from within itself with arguments.callee
            var fn= arguments.callee;

            //'this' at this level is the jquery object list matching your given selector
            //we equate fn.prototype to this 
            //thus when we call a new instance of root, we are returned 'this'
            fn.prototype= this;

            fn.value= function(){
                //Note: "new this" will work in the below line of code as well,
                //because in the current context, 'this' is fn;
                //I use fn to make the code more intuitive to understand;
                var context= new fn; 

                console.log(context, fn.prototype); //test
                return context.html(); //test
            }

            return this;
        }
    }

    //you can obviously append additional nested properties in this manner as well
    options.root.position= function(){
        var context= new this; //in this context, fn is undefined, so we leverage 'this'

        console.log(context, this.prototype); //test
        return context.offset(); //test
    }

    //don't forget to extend in the end :)
    $.fn.extend(options);

})(jQuery);

;$(function(){
    var div= $('div#div')
        .root();

    console.log(div.root.value());
    console.log(div.root.position());
});

答案 4 :(得分:4)

如果你想以这种方式使用jQuery:

$("*").namespace.do();

然后目前没有插件可以做到这一点。 (我找不到John Resig的jquery.space插件,它显然已停止在jQuery 1.4中工作,也没有找到Gilberto Saraiva插件,显然没有按预期工作)。我很乐意看看John的功能,看看为什么它停止工作,以及如何使它工作,坦率地说,这将是创建整洁命名空间的最佳方法。

根据http://malnotna.wordpress.com/2009/01/12/jquery-namespace-support/另一种方法是将命名空间作为(使用Ariel Flesler的jQuery.Modularize):

$("*").namespace().do()

但是这样的语法并不“漂亮”。我们也将结果从一个函数传递给另一个函数。

我创建命名空间的方法不是将命名空间放在最后,而是在$的开头,所以我们的$('*')。namespace语法变为:

$.namespace("*").do()

奇怪的是,我不知道为什么没有提到这种方法,因为它很容易让你创建无文件名称空间而不会覆盖现有的函数(通过使用$ .sub())。此外,使其工作不需要任何东西。所以:

(function($){
    $.namespace = $.sub();
    $.fn.test = function(){ return 1 };              
    $.namespace.fn.test = function() { return 2};
})(jQuery);

console.log($('*').test(), $.namespace('*').test());

你准备好了。

答案 5 :(得分:2)

根据您的目标,jQuery的插件架构可能正是您所寻找的:

$.fn.myPlugin = function() {
  return $(this).each(function() {
    // do stuff
  });
};

或......

$.fn.myPlugin = function() {
  var myNamespace = {
    // your stuff
  };
};

这真的取决于你想要做什么。

http://docs.jquery.com/Plugins/Authoring

答案 6 :(得分:2)

查看此博客:http://javascriptweblog.wordpress.com/2010/12/07/namespacing-in-javascript/

自我调用的动态命名空间是我之前使用的:

var myApp = {};
(function(context) {
    var id = 0;

    context.next = function() {
        return id++;
    };

    context.reset = function() {
        id = 0;
    } 
})(myApp); 

window.console && console.log(
    myApp.next(),
    myApp.next(),
    myApp.reset(),
    myApp.next()
); //0, 1, undefined, 0

答案 7 :(得分:1)

所有归功于@Diego Fluery,我只是拿着他的幻灯片并制作了一个可运行的代码原型,但是如果你走这条路线可能会节省几分钟:

<!DOCTYPE html>
<html>
<head>
<script type="application/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="application/javascript">

    $(document).ready(function() {
        (function () {
            $.fn.AppRedirect = function() {
                this.sendRequest = parts.sendRequest;
                this.doRedirect = parts.doRedirect;

                return this;
            }

            var parts = {

                doRedirect: function() {
                    console.log('doRedirect');
                },

                sendRequest: function() {
                    console.log('sendRequest');
                }

            };
        })();

        $("body").AppRedirect().sendRequest();
        $("body").AppRedirect().doRedirect();
    });     

</script>
</head>
<body>
</body>
</html>
相关问题