最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

What does "var dialogs = {};" mean in jQueryjavascript? - Stack Overflow

programmeradmin3浏览0评论

Sorry to bother you all here but I am still trying to understand more about some javascript code that I am working on. I just recently asked a question about dialogs[id] = $(); Now I look further up the code and see something else I am not familiar with.

Can someone explain what the purpose of "var dialogs = {}" is in this context. Thanks,

 $(function () {
// Cache for dialogs
var dialogs = {};

var getValidationSummaryErrors = function ($form) {
    // We verify if we created it beforehand
    var errorSummary = $form.data('validation-summary-errors');
    if (!errorSummary) {
        errorSummary = $('<div class="validation-summary-errors"><span>Please correct the errors and try again.</span><ul></ul></div>')
            .insertBefore($form);

        // Remember that we created it
        $form.data('validation-summary-errors', errorSummary);
    }

    return errorSummary;
};

var formSubmitHandler = function (e) {
    var $form = $(this);

    // We check if jQuery.validator exists on the form
    if (!$form.valid || $form.valid()) {
        $.post($form.attr('action'), $form.serializeArray())
            .done(function (json) {
                json = json || {};

                // In case of success, we redirect to the provided URL or the same page.
                if (json.success) {
                    location = json.redirect || location.href;
                } else if (json.errors) {
                    var errorSummary = getValidationSummaryErrors($form);

                    var items = $.map(json.errors, function (error) {
                        return '<li>' + error + '</li>';
                    }).join('');

                    var ul = errorSummary
                        .find('ul')
                        .empty()
                        .append(items);
                }
            });
    }

    // Prevent the normal behavior since we opened the dialog
    e.preventDefault();
};

var loadAndShowDialog = function (id, link, url) {
    var separator = url.indexOf('?') >= 0 ? '&' : '?';

    // Save an empty jQuery in our cache for now.
    dialogs[id] = $();

    // Load the dialog with the content=1 QueryString in order to get a PartialView
    $.get(url + separator + 'content=1')
        .done(function (content) {
            dialogs[id] = $('<div class="modal-popup">' + content + '</div>')
                .hide() // Hide the dialog for now so we prevent flicker
                .appendTo(document.body)
                .filter('div') // Filter for the div tag only, script tags could surface
                .dialog({ // Create the jQuery UI dialog
                    title: link.data('dialog-title'),
                    modal: true,
                    resizable: true,
                    draggable: true,
                    width: link.data('dialog-width') || 300
                })
                .find('form') // Attach logic on forms
                    .submit(formSubmitHandler)
                .end();
        });
};

// List of link ids to have an ajax dialog
var links = ['logonLink', 'registerLink'];

$.each(links, function (i, id) {
    $('#' + id).click(function (e) {
        var link = $(this),
            url = link.attr('href');

        if (!dialogs[id]) {
            loadAndShowDialog(id, link, url);
        } else {
            dialogs[id].dialog('open');
        }

        // Prevent the normal behavior since we use a dialog
        e.preventDefault();
    });
});

});

Note that this is the plete javascript. There's nothing more that's not shown here.

Also: Is it needed?

Sorry to bother you all here but I am still trying to understand more about some javascript code that I am working on. I just recently asked a question about dialogs[id] = $(); Now I look further up the code and see something else I am not familiar with.

Can someone explain what the purpose of "var dialogs = {}" is in this context. Thanks,

 $(function () {
// Cache for dialogs
var dialogs = {};

var getValidationSummaryErrors = function ($form) {
    // We verify if we created it beforehand
    var errorSummary = $form.data('validation-summary-errors');
    if (!errorSummary) {
        errorSummary = $('<div class="validation-summary-errors"><span>Please correct the errors and try again.</span><ul></ul></div>')
            .insertBefore($form);

        // Remember that we created it
        $form.data('validation-summary-errors', errorSummary);
    }

    return errorSummary;
};

var formSubmitHandler = function (e) {
    var $form = $(this);

    // We check if jQuery.validator exists on the form
    if (!$form.valid || $form.valid()) {
        $.post($form.attr('action'), $form.serializeArray())
            .done(function (json) {
                json = json || {};

                // In case of success, we redirect to the provided URL or the same page.
                if (json.success) {
                    location = json.redirect || location.href;
                } else if (json.errors) {
                    var errorSummary = getValidationSummaryErrors($form);

                    var items = $.map(json.errors, function (error) {
                        return '<li>' + error + '</li>';
                    }).join('');

                    var ul = errorSummary
                        .find('ul')
                        .empty()
                        .append(items);
                }
            });
    }

    // Prevent the normal behavior since we opened the dialog
    e.preventDefault();
};

var loadAndShowDialog = function (id, link, url) {
    var separator = url.indexOf('?') >= 0 ? '&' : '?';

    // Save an empty jQuery in our cache for now.
    dialogs[id] = $();

    // Load the dialog with the content=1 QueryString in order to get a PartialView
    $.get(url + separator + 'content=1')
        .done(function (content) {
            dialogs[id] = $('<div class="modal-popup">' + content + '</div>')
                .hide() // Hide the dialog for now so we prevent flicker
                .appendTo(document.body)
                .filter('div') // Filter for the div tag only, script tags could surface
                .dialog({ // Create the jQuery UI dialog
                    title: link.data('dialog-title'),
                    modal: true,
                    resizable: true,
                    draggable: true,
                    width: link.data('dialog-width') || 300
                })
                .find('form') // Attach logic on forms
                    .submit(formSubmitHandler)
                .end();
        });
};

// List of link ids to have an ajax dialog
var links = ['logonLink', 'registerLink'];

$.each(links, function (i, id) {
    $('#' + id).click(function (e) {
        var link = $(this),
            url = link.attr('href');

        if (!dialogs[id]) {
            loadAndShowDialog(id, link, url);
        } else {
            dialogs[id].dialog('open');
        }

        // Prevent the normal behavior since we use a dialog
        e.preventDefault();
    });
});

});

Note that this is the plete javascript. There's nothing more that's not shown here.

Also: Is it needed?

Share Improve this question edited Feb 2, 2012 at 7:59 kapa 78.8k21 gold badges165 silver badges178 bronze badges asked Feb 2, 2012 at 7:39 Samantha J T StarSamantha J T Star 33k89 gold badges257 silver badges441 bronze badges 1
  • Added the javascript tag because this is not a jQuery-specific question. – kapa Commented Feb 2, 2012 at 8:00
Add a ment  | 

3 Answers 3

Reset to default 5

It instantiates a new Object without any own properties or methods. Basically the same as saying

var dialogs = new Object();

The {} notation is called an object literal.


It is needed in this code. The variable dialogs is used to keep track of existing (already created) dialogs, so they don't have to be created each time they are opened. Several lines reference this variable if you take a closer look. dialogs is declared at the top (var dialogs = {}) so every other function at the same level can use it (read up on variable scope).

I have marked the places in your code when the dialogs object is used. Don't let the dialogs[id] notation fool you - dialogs is not an array (Javascript has no associative arrays), but an object here, so it is equivalent to dialogs.id.

$(function () { //this is used not to pollute the global scope

var dialogs = {}; //HERE - dialogs is declared in this local scope

...

var loadAndShowDialog = function (id, link, url) {
    var separator = url.indexOf('?') >= 0 ? '&' : '?';

    dialogs[id] = $(); //HERE - dialogs.id will be an empty jQuery object

    $.get(url + separator + 'content=1')
        .done(function (content) {
            //HERE - dialogs.id bees a (jQuery-wrapped) div 
            //with the appropriate content
            dialogs[id] = $('<div class="modal-popup">' + content + '</div>')
               ...
        });
};

...
$.each(links, function (i, id) {
    $('#' + id).click(function (e) {
        ...  
        if (!dialogs[id]) { //HERE - if a dialog with this id does not exist
            loadAndShowDialog(id, link, url); //load a new one
        } else { //otherwise
            dialogs[id].dialog('open'); //HERE - open the existing dialog
        }
        ...
    });
});

});

{} is the shortcut for creating a new object (like [] is for arrays), so var dialogs = {} just creates an empty object without any properties.

It declares an empty Javascript object, which can then have properties dynamically added to it for storage.

EDIT: Note that there are two ways of accessing properties on an object in Javascript. The first is using "dot notation", i.e. object.property.

The second is using brackets, e.g. object['property']. They are more or less the same thing.

Also, because Javascript is a dynamic language, if you set a property that doesn't exist on the object, it creates it for you, then sets it.

Given this, you should be able to spot where this dialogs object is used in your code. Hint: It uses the latter notation. :-)

发布评论

评论列表(0)

  1. 暂无评论