jQuery:类和命名空间

时间:2011-08-16 20:13:10

标签: jquery

我被告知要在我的jQuery代码中开始使用Classes和Namespacing,而对于我们正在构建的新应用程序,我们将使代码变得非常简单和光滑。例如,在登录页面上使用以下代码来加载所有内容,然后将其淡入:

        // Hide the content and fadein the spinner
        jQuery(document).ready(function()
        {
            $('#hide').hide();
            $('body').append('<div id="loading">loading...</div>');
            $("#loading").hide();
            setTimeout($('#loading').fadeIn(), 200);
        });

        // When all content has loaded, fadeout the spinner and THEN fadein the content
        jQuery(window).load(function ()
        {
            $("#loading").fadeOut("slow", function ()
            {
                $("#loading").remove();
                clearInterval(loadingAnim);
                $("#hide").fadeIn("slow");
            });
        });

        var lastx = 0;

        var loadingAnim = setInterval(function () { UpdateSpinner("#loading", 42, 504); }, 42);

        function UpdateSpinner(target, step, width)
        {
            $(target).css("background-position", "0 " + lastx + "px");
            lastx = (lastx - step) % width;
        }

如何使用名称间距和类更简单?

我在哪里看过这个例子:http://static.neow.in/js/pegasus/mainpage.js

由于

3 个答案:

答案 0 :(得分:0)

您可以创建全局命名空间并定义其下的所有成员。这样您就可以避免在多个开发人员使用同一个应用程序的庞大应用程序中发生名称冲突。

var myApp = {};

myApp.lastx = 0;

myApp.loadingAnim = setInterval(function () { myApp.UpdateSpinner("#loading", 42, 504); }, 42);

        myApp.UpdateSpinner = function()(target, step, width)
        {
            $(target).css("background-position", "0 " + lastx + "px");
            myApp.lastx = (lastx - step) % width;
        }

答案 1 :(得分:0)

1-您可以将代码包装在

jQuery(function($) { 
    /*Your code goes here */
})

而不是:

jQuery(document).ready(function() {

});

如你所见,更具可读性。

2-您也可以将以下代码放在上一个函数中,因为只有在已经加载了所有内容时才调用它,这样您就只能有一个可读的代码块:

$("#loading").fadeOut("slow", function ()
            {
                $("#loading").remove();
                clearInterval(loadingAnim);
                $("#hide").fadeIn("slow");
            });

所以你可以删除:

// When all content has loaded, fadeout the spinner and THEN fadein the content
        jQuery(window).load(function ()
        {
{})

部分并将内容保留在外部函数中。

3-如果你真的希望你的应用程序不受命名空间问题的影响,那么你可以做的最好的事情是将所有代码包装在一个匿名(也就是未命名的)函数之间,就像我在第1点和下一个代码中所做的那样样品:

(function( ) {  // Define an anonymous function.  No name means no global symbols
    // Code goes here
    // Any variables are safely nested within the function,
    // so no global symbols are created.
})( );          // End the function definition and invoke it.

希望它对你有所帮助。

答案 2 :(得分:0)

它听起来不像是jQuery特定的请求,而是更多的使用JavaScript 请求。它听起来像是要求您使代码更加封装和面向对象。

How do I declare a namespace in JavaScript?JavaScript: Class.method vs. Class.prototype.method上的答案是一个非常好的起点。