Java Script Translation

Discussion in 'Software' started by JJJIrish05, Nov 12, 2009.

  1. JJJIrish05

    JJJIrish05 Sergeant

    I'm still kind of new to javascript and I'm trying to interpret some code I found but they used a bunch of short hand stuff that I don't understand yet. So can someone translate this code for me for I know what its doing:

    Code:
    savePreferences : function () { 
            var iNettuts = this, 
                $ = this.jQuery, 
                settings = this.settings, 
                cookieString = ''; 
                 
            if(!settings.saveToCookie) {return;} 
             
            /* Assemble the cookie string */ 
            $(settings.columns).each(function(i){ 
                cookieString += (i===0) ? '' : '|'; 
                $(settings.widgetSelector,this).each(function(i){ 
                    cookieString += (i===0) ? '' : ';'; 
                    /* ID of widget: */ 
                    cookieString += $(this).attr('id') + ','; 
                    /* Color of widget (color classes) */ 
                    cookieString += $(this).attr('class').match(/\bcolor-[\w]{1,}\b/) + ','; 
                    /* Title of widget (replaced used characters) */ 
                    cookieString += $('h3:eq(0)',this).text().replace(/\|/g,'[-PIPE-]').replace(/,/g,'[-COMMA-]') + ','; 
                    /* Collapsed/not collapsed widget? : */ 
                    cookieString += $(settings.contentSelector,this).css('display') === 'none' ? 'collapsed' : 'not-collapsed'; 
                }); 
            }); 
             
            /* AJAX call to store string on database */ 
            $.post("iNettuts_rpc.php","value="+cookieString); 
             
        },
     
  2. SWario

    SWario Sergeant

    I've added comments, but I am by no means an expert in either JavaScript or jQuery.

    PHP:
    /*
      Function named "savePreferences", probably a method for an object,
      presumably for saving preferences for something.
      Seems to be declared in Literal Notation.  Was this all within another
      set of brackets?  Having all of the code would help.
    */
    savePreferences : function () {
      
    // sets "this object" to the variable "iNettuts"
      
    var iNettuts this,

      
    /* assigns an instance of "this object"'s jQuery to the global $ (unless $
         was already declared) */
      
    $ = this.jQuery,

      
    /* assigns the property "settings" of object "this" to the global "settings"
         (unless settings was declared earlier) */
      
    settings this.settings,

      
    // assigns a blank string to the global "cookieString"
      
    cookieString '';
      
      
    /* assuming "settings" is an object itself, it has a property "saveToCookie"
         "IF the property saveToCookie's value results in TRUE, RETURN nothing"
         (exits the function, because you can only return one value)
         "ELSE, continue" */
      
    if(!settings.saveToCookie) {return;}
      
      
    /* Assemble the cookie string */
      // run jQuery "each" on settings.columns using the passed function
      
    $(settings.columns).each(function(i){

        
    /* ternary form of an IF statement normally written:
           if (i===0) { cookieString += ''; } else { cookieString += '|'; } */
        
    cookieString += (i===0) ? '' '|';

        
    /* run jQuery "each" on settings.widgetSelector with the context of
           "this object" using the passed function */
        
    $(settings.widgetSelector,this).each(function(i){

          
    /* ternary IF again:
             if (i===0) { cookieString += ''; } else { cookieString += ';'; } */
          
    cookieString += (i===0) ? '' ';';

          
    /* ID of widget: */
          /* add the value of "this object's" "id" to cookieString
          cookieString += $(this).attr('id') + ',';

          /* Color of widget (color classes) */
          /* add the value of "this object's" "class" to cookieString IF it
             matches the Regular Expression provided (\bcolor-[\w]{1,}\b),
             then add ',' */
          
    cookieString += $(this).attr('class').match(/\bcolor-[\w]{1,}\b/) + ',';

          
    /* Title of widget (replaced used characters) */
          /* add the text within first h3 tag in the context of "this" AFTER
             performing two REPLACE operations on it with Regular Expressions */
          
    cookieString += $('h3:eq(0)',this).text().replace(/\|/g,'[-PIPE-]')
            .
    replace(/,/g,'[-COMMA-]') + ',';

          
    /* Collapsed/not collapsed widget? : */
          /* ternary IF:
             if (settings.contentSelector's display STRICTLY EQUALS 'none')
             { cookieString += 'collapsed'; } else
             { cookieString += 'not-collapsed';} */
          
    cookieString += $(settings.contentSelector,this).css('display')
            === 
    'none' 'collapsed' 'not-collapsed';
        }); 
    // end second "each"
      
    }); // end first "each"
      
      /* AJAX call to store string on database */
      /* Calls the page "iNettuts_rpc.php" and sends it the key "value" with
         the value of the variable "cookieString"
      $.post("iNettuts_rpc.php","value="+cookieString);

    }, // end "savePreferences"
    Beware of globals and $. You should probably not assign jQuery to $ unless you really need to. Also, the syntax for settings variables at the beginning of "savePreferences" seems mixed up with declaring properties of a function, but I could be wrong.

    See jQuery Core "each" function.

    I so wish the PHP tag followed standard syntax highlighting so that the comments were green.
     
  3. JJJIrish05

    JJJIrish05 Sergeant

    so what is "this"? is it like just the entire page?

    here's the entire source for the file:
    Code:
    /* 
     * Script from NETTUTS.com [by James Padolsey] V.2 (ENHANCED, WITH COOKIES!!!) 
     * @requires jQuery($), jQuery UI & sortable/draggable UI modules & jQuery COOKIE plugin 
     */ 
     
    var iNettuts = { 
         
        jQuery : $, 
         
        settings : { 
            columns : '.column', 
            widgetSelector: '.widget', 
            handleSelector: '.widget-head', 
            contentSelector: '.widget-content', 
             
            /* If you don't want preferences to be saved change this value to 
                false, otherwise change it to the name of the cookie: */ 
            saveToCookie: 'inettuts-widget-preferences', 
             
            widgetDefault : { 
                movable: true, 
                removable: true, 
                collapsible: true, 
                editable: true, 
                colorClasses : ['color-yellow', 'color-red', 'color-blue', 'color-white', 'color-orange', 'color-green'] 
            }, 
            widgetIndividual : {} 
        }, 
     
        init : function () { 
            this.attachStylesheet('inettuts.js.css'); 
            this.sortWidgets(); 
            this.addWidgetControls(); 
            this.makeSortable(); 
        }, 
         
        getWidgetSettings : function (id) { 
            var $ = this.jQuery, 
                settings = this.settings; 
            return (id&&settings.widgetIndividual[id]) ? $.extend({},settings.widgetDefault,settings.widgetIndividual[id]) : settings.widgetDefault; 
        }, 
         
        addWidgetControls : function () { 
            var iNettuts = this, 
                $ = this.jQuery, 
                settings = this.settings; 
                 
            $(settings.widgetSelector, $(settings.columns)).each(function () { 
                var thisWidgetSettings = iNettuts.getWidgetSettings(this.id); 
                if (thisWidgetSettings.removable) { 
                    $('<a href="#" class="remove">CLOSE</a>').mousedown(function (e) { 
                        /* STOP event bubbling */ 
                        e.stopPropagation();     
                    }).click(function () { 
                        if(confirm('This widget will be removed, ok?')) { 
                            $(this).parents(settings.widgetSelector).animate({ 
                                opacity: 0     
                            },function () { 
                                $(this).wrap('<div/>').parent().slideUp(function () { 
                                    $(this).remove(); 
                                }); 
                            }); 
                        } 
                        return false; 
                    }).appendTo($(settings.handleSelector, this)); 
                } 
                 
                if (thisWidgetSettings.editable) { 
                    $('<a href="#" class="edit">EDIT</a>').mousedown(function (e) { 
                        /* STOP event bubbling */ 
                        e.stopPropagation();     
                    }).toggle(function () { 
                        $(this).css({backgroundPosition: '-66px 0', width: '55px'}) 
                            .parents(settings.widgetSelector) 
                                .find('.edit-box').show().find('input').focus(); 
                        return false; 
                    },function () { 
                        $(this).css({backgroundPosition: '', width: '24px'}) 
                            .parents(settings.widgetSelector) 
                                .find('.edit-box').hide(); 
                        return false; 
                    }).appendTo($(settings.handleSelector,this)); 
                    $('<div class="edit-box" style="display:none;"/>') 
                        .append('<ul><li class="item"><label>Change the title?</label><input value="' + $('h3',this).text() + '"/></li>') 
                        .append((function(){ 
                            var colorList = '<li class="item"><label>Available colors:</label><ul class="colors">'; 
                            $(thisWidgetSettings.colorClasses).each(function () { 
                                colorList += '<li class="' + this + '"/>'; 
                            }); 
                            return colorList + '</ul>'; 
                        })()) 
                        .append('</ul>') 
                        .insertAfter($(settings.handleSelector,this)); 
                } 
                 
                if (thisWidgetSettings.collapsible) { 
                    $('<a href="#" class="collapse">COLLAPSE</a>').mousedown(function (e) { 
                        /* STOP event bubbling */ 
                        e.stopPropagation();     
                    }).click(function(){ 
                        $(this).parents(settings.widgetSelector).toggleClass('collapsed'); 
                        /* Save prefs to cookie: */ 
                        iNettuts.savePreferences(); 
                        return false;     
                    }).prependTo($(settings.handleSelector,this)); 
                } 
            }); 
             
            $('.edit-box').each(function () { 
                $('input',this).keyup(function () { 
                    $(this).parents(settings.widgetSelector).find('h3').text( $(this).val().length>20 ? $(this).val().substr(0,20)+'...' : $(this).val() ); 
                    iNettuts.savePreferences(); 
                }); 
                $('ul.colors li',this).click(function () { 
                     
                    var colorStylePattern = /\bcolor-[\w]{1,}\b/, 
                        thisWidgetColorClass = $(this).parents(settings.widgetSelector).attr('class').match(colorStylePattern) 
                    if (thisWidgetColorClass) { 
                        $(this).parents(settings.widgetSelector) 
                            .removeClass(thisWidgetColorClass[0]) 
                            .addClass($(this).attr('class').match(colorStylePattern)[0]); 
                        /* Save prefs to cookie: */ 
                        iNettuts.savePreferences(); 
                    } 
                    return false; 
                     
                }); 
            }); 
             
        }, 
         
        attachStylesheet : function (href) { 
            var $ = this.jQuery; 
            return $('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head'); 
        }, 
         
        makeSortable : function () { 
            var iNettuts = this, 
                $ = this.jQuery, 
                settings = this.settings, 
                $sortableItems = (function () { 
                    var notSortable = ''; 
                    $(settings.widgetSelector,$(settings.columns)).each(function (i) { 
                        if (!iNettuts.getWidgetSettings(this.id).movable) { 
                            if(!this.id) { 
                                this.id = 'widget-no-id-' + i; 
                            } 
                            notSortable += '#' + this.id + ','; 
                        } 
                    }); 
                    return $('> li:not(' + notSortable + ')', settings.columns); 
                })(); 
             
            $sortableItems.find(settings.handleSelector).css({ 
                cursor: 'move' 
            }).mousedown(function (e) { 
                $sortableItems.css({width:''}); 
                $(this).parent().css({ 
                    width: $(this).parent().width() + 'px' 
                }); 
            }).mouseup(function () { 
                if(!$(this).parent().hasClass('dragging')) { 
                    $(this).parent().css({width:''}); 
                } else { 
                    $(settings.columns).sortable('disable'); 
                } 
            }); 
     
            $(settings.columns).sortable({ 
                items: $sortableItems, 
                connectWith: $(settings.columns), 
                handle: settings.handleSelector, 
                placeholder: 'widget-placeholder', 
                forcePlaceholderSize: true, 
                revert: 300, 
                delay: 100, 
                opacity: 0.8, 
                containment: 'document', 
                start: function (e,ui) { 
                    $(ui.helper).addClass('dragging'); 
                }, 
                stop: function (e,ui) { 
                    $(ui.item).css({width:''}).removeClass('dragging'); 
                    $(settings.columns).sortable('enable'); 
                    /* Save prefs to cookie: */ 
                    iNettuts.savePreferences(); 
                } 
            }); 
        }, 
         
        savePreferences : function () { 
            var iNettuts = this, 
                $ = this.jQuery, 
                settings = this.settings, 
                cookieString = ''; 
                 
            if(!settings.saveToCookie) {return;} 
             
            /* Assemble the cookie string */ 
            $(settings.columns).each(function(i){ 
                cookieString += (i===0) ? '' : '|'; 
                $(settings.widgetSelector,this).each(function(i){ 
                    cookieString += (i===0) ? '' : ';'; 
                    /* ID of widget: */ 
                    cookieString += $(this).attr('id') + ','; 
                    /* Color of widget (color classes) */ 
                    cookieString += $(this).attr('class').match(/\bcolor-[\w]{1,}\b/) + ','; 
                    /* Title of widget (replaced used characters) */ 
                    cookieString += $('h3:eq(0)',this).text().replace(/\|/g,'[-PIPE-]').replace(/,/g,'[-COMMA-]') + ','; 
                    /* Collapsed/not collapsed widget? : */ 
                    cookieString += $(settings.contentSelector,this).css('display') === 'none' ? 'collapsed' : 'not-collapsed'; 
                }); 
            }); 
            $.cookie(settings.saveToCookie,cookieString,{ 
                expires: 10 
                //path: '/' 
            }); 
        }, 
         
        sortWidgets : function () { 
            var iNettuts = this, 
                $ = this.jQuery, 
                settings = this.settings; 
             
            /* Read cookie: */ 
            var cookie = $.cookie(settings.saveToCookie); 
            if(!settings.saveToCookie||!cookie) { 
                /* Get rid of loading gif and show columns: */ 
                $('body').css({background:'#000'}); 
                $(settings.columns).css({visibility:'visible'}); 
                return; 
            } 
             
            /* For each column */ 
            $(settings.columns).each(function(i){ 
                 
                var thisColumn = $(this), 
                    widgetData = cookie.split('|')[i].split(';'); 
                     
                $(widgetData).each(function(){ 
                    if(!this.length) {return;} 
                    var thisWidgetData = this.split(','), 
                        clonedWidget = $('#' + thisWidgetData[0]), 
                        colorStylePattern = /\bcolor-[\w]{1,}\b/, 
                        thisWidgetColorClass = $(clonedWidget).attr('class').match(colorStylePattern); 
                     
                    /* Add/Replace new colour class: */ 
                    if (thisWidgetColorClass) { 
                        $(clonedWidget).removeClass(thisWidgetColorClass[0]).addClass(thisWidgetData[1]); 
                    } 
                     
                    /* Add/replace new title (Bring back reserved characters): */ 
                    $(clonedWidget).find('h3:eq(0)').html(thisWidgetData[2].replace(/\[-PIPE-\]/g,'|').replace(/\[-COMMA-\]/g,',')); 
                     
                    /* Modify collapsed state if needed: */ 
                    if(thisWidgetData[3]==='collapsed') { 
                        /* Set CSS styles so widget is in COLLAPSED state */ 
                        $(clonedWidget).addClass('collapsed'); 
                    } 
     
                    $('#' + thisWidgetData[0]).remove(); 
                    $(thisColumn).append(clonedWidget); 
                }); 
            }); 
             
            /* All done, remove loading gif and show columns: */ 
            $('body').css({background:'#000'}); 
            $(settings.columns).css({visibility:'visible'}); 
        } 
       
    }; 
     
    iNettuts.init();
    and if anyone interested here's the site for the open source project that I got this from: http://net.tutsplus.com/tutorials/javascript-ajax/inettuts/
     
    Last edited: Nov 18, 2009
  4. SWario

    SWario Sergeant

    The keyword "this" is a reference to whatever object/element is in the immediate context of the keyword. For example:
    PHP:
    <p onClick="function(this)">Some paragraph text is here.</p>
    Here, the keyword "this" refers to the P tag.

    In the case of the code you posted, I would guess "this" refers to the object "iNettuts", which is then stored in a variable local to each function.
     

MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds