2

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 complete javascript. There's nothing more that's not shown here.

Also: Is it needed?

kapa
  • 77,694
  • 21
  • 158
  • 175
Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427

3 Answers3

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 becomes 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
        }
        ...
    });
});

});
Community
  • 1
  • 1
kapa
  • 77,694
  • 21
  • 158
  • 175
  • 1
    Without any *own* properties or methods. – Gumbo Feb 02 '12 at 07:42
  • Just adding: you're using the `dialogs` object in your `loadAndShowDialog` function (from your previous question). by calling `dialogs[id]`, you're accessing a dynamic property of the object. It's like trying to set `dialogs.foo = "bar"`, but the `foo` part is dynamic, unknown, and can be changed. – Richard Neil Ilagan Feb 02 '12 at 08:07
5

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

oezi
  • 51,017
  • 10
  • 98
  • 115
1

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. :-)

GregL
  • 37,147
  • 8
  • 62
  • 67
  • 1
    Very quick answer :-) But is it even used here in the script? Note that I was previously asking also if dialogs[id] = $(); was needed. One person suggested maybe not. – Samantha J T Star Feb 02 '12 at 07:41
  • @SamanthaJ I have updated my answer. Can you spot the places where it is used now? – GregL Feb 02 '12 at 07:53