3

I've been asked to add some new jQuery functionality to this file, although I have never written any jQuery in this way(seems to be loads of functions written all under one variable called 'companyname'). So currently I need to edit some new jQuery in this file under what seems to be the "menu :" function which can be found in the JavaScript part of code near the end. So my question is, what is this style of writing jQuery called? Is it possibles isn't to add new sections to it. For example called, 'newcode:'? Or do you I need to be doing something special to add code to this massive variable? Even if someone can give me a name for this type if code I can look for some tutorials on it.

Also the other bit of code I have included is present directly on the home page within the head tag and script tags, and appears to call the menu function directly. How comes no other functions need to be called in the head tag(there is one more I think) can they just be called somewhere else like in an A tag or something?

Thank you all for reading.

Daniel.

P.s 'init :' seems to be included in all/most functions, why is this? What is it for?

head.ready("main", function() {
    setTimeout(function () {//FF 3.6 Fix
        sonypro.menu.init();
    }, 500);
});



// JavaScript Document
(function( $ ){

var companyname =  {

    helper : {
        maxHeight : function(o) {

            var max = 0;

            $(o).each(function() {
                if (max < $(this).outerHeight()) {
                    max = $(this).outerHeight(true);
                }
            }); 

            return max;
        },
        maxValue: function(array){

            return Math.max.apply(Math,array);

        },
        isEmpty : function(o) {

            // For checking if a string is blank, null or undefined
            return (!o || /^\s*$/.test(o));

        },
        createElement : {
            script : function(source) {
                var script = document.createElement('script');
                script.type = 'text/javascript';
                script.src = source;
                document.body.appendChild(script);
            }
        }
    },

    article: {
        margin_fix: function() {
            if ($('.pge-article-detail').index()!=-1)
                $('.lte-ie8 .article-section p').css('margin-bottom',0);
        }
    },

    product: {
        slider : {
            init : function(options) {

                var settings = $.extend({
                    'visible' : 5,
                    'autoHeight' : false
                }, options),
                id = settings.id

                $('#'+id).jcarousel({
                    animation : 1000,
                    scroll: settings.visible,
                    initCallback: function(carousel) {
                        if(settings.autoHeight) {
                            _maxHeight = companyname.helper.maxHeight('#'+id+' > li');
                            $("#"+id+" .jcarousel-clip, #"+id+ " .jcarousel-item").css("height", _maxHeight);
                        }
                        $("#"+id).mousewheel(function(event, delta) {
                            if (delta > 0) {
                                carousel.prev();
                            }
                            else if (delta < 0) {
                                carousel.next();
                            }

                            return false; // prevent default
                        });
                    }
                });
            }
        },
        image_changer : {
            video: {
                is_set: false,
                timer: 0,
                clear_timer: function () {
                    clearTimeout(companyname.product.image_changer.video.timer);
                    companyname.product.image_changer.video.timer = 0;
                },
                play: function () {
                    companyname.product.image_changer.video.clear_timer();
                    companyname.product.image_changer.video.timer = setTimeout(function () {sublimevideo.play();},500);
                },
                pause: function () {
                    companyname.product.image_changer.video.clear_timer();
                    sublimevideo.pause();
                },
                stop: function () {
                    companyname.product.image_changer.video.clear_timer();
                    sublimevideo.stop();
                }
            },
            settings: {
                thumbs : 'a.thumbnail',
                sticky : 'div#main-visual',
                visual_wrapper_class : '.visual'
            },
            init: function(options) {
                this.settings = $.extend(this.settings,options);
                settings = this.settings,
                thumbnails = $(settings.thumbs),
                image = $(settings.image),
                visual_wrapper = $('.visual'),

                sticky = $(settings.sticky);

                thumbnails.on('mouseenter',function(){
                    var $this = $(this),
                    thumb_detail = visual_wrapper.children('.thumb-'+$this.index());
                    companyname.product.image_changer.load_img($this,thumb_detail);
                    companyname.product.image_changer.change_img(thumb_detail,true);
                    if (companyname.product.image_changer.video.is_set)
                        companyname.product.image_changer.video.pause();

                })
                .on('mouseleave',function(){
                    var $this = $(this),
                    thumb_detail = visual_wrapper.children('.thumb-'+$this.index());                        
                    companyname.product.image_changer.change_img(thumb_detail,false);
                    if (companyname.product.image_changer.video.is_set)
                        companyname.product.image_changer.video.play();
                })
                .on('focus',function(){
                    var $this = $(this),
                    thumb_detail = visual_wrapper.children('.thumb-'+$this.index());
                    companyname.product.image_changer.load_img($this,thumb_detail);
                    companyname.product.image_changer.change_img(thumb_detail,true);
                    if (companyname.product.image_changer.video.is_set)
                        companyname.product.image_changer.video.pause();
                })
                .on('blur',function(){
                    var $this = $(this),
                    thumb_detail = visual_wrapper.children('.thumb-'+$this.index());
                    companyname.product.image_changer.change_img(thumb_detail,false);
                    if (companyname.product.image_changer.video.is_set)
                        companyname.product.image_changer.video.play();
                })
                .on('click',function(e){
                    e.preventDefault();
                    if (companyname.product.image_changer.video.is_set)
                        companyname.product.image_changer.video.stop();
                    $('#image-gallery').click();
                })

            },
            change_img : function(thumb_detail,show) {
                if(show) {
                    sticky.hide();
                    thumb_detail.show();
                }
                else {
                    sticky.show();
                    thumb_detail.hide();
                }

            },
            load_img : function(thumb,thumb_detail){
                if(!thumb_detail.length) {
                    thumb_detail = $('<img />').attr({
                        'src' : thumb.attr('href'),
                        'class' : 'detail-image thumb-'+thumb.index()
                    }).appendTo(visual_wrapper);
                }
            }

        }
    },

    accordion: {
        settings : {
            'heading' : 'h1.expand-collapse-heading',
            'content' : 'div.expand-collapse-content',
            'collapsed_class' : 'collapsed',
            'collapse_toggle' : 'a#collapse-toggle',
            'accordion' : true,
            'animation' : true,
            'jScrollPane' : false
        },
        init : function(options) {
            this.settings = $.extend(this.settings,options);
            settings = this.settings,
            collapse_state = true,
            all_headings = $(settings.heading),
            all_contents = $(settings.content),
            collapse_toggle = $(settings.collapse_toggle),
            collapse_text = collapse_toggle.find('span');

            $('.lte-ie8 '+settings.heading).prepend('<div class="icon"></div>');

            if(settings.accordion) {
                collapse_toggle.hide();
            } else {
                collapse_text.eq(1).hide();
            }

            all_headings.not(':first').addClass(settings.collapsed_class);

            all_contents.not(':first').hide();

            all_headings.on('click',function(e){
                e.preventDefault();
                var $this = $(this),
                content = $this.next(settings.content),
                collapsed = settings.collapsed_class;

                if($this.hasClass(collapsed)) {
                    companyname.accordion.expand($this,content);

                    if(settings.accordion) {
                        companyname.accordion.collapse(all_headings.not($this),all_contents.not(content));
                    }
                } else {
                    companyname.accordion.collapse($this,content);
                }
                collapse_state = (all_headings.filter('.'+settings.collapsed_class).length == all_headings.length) ? companyname.accordion.collapse_toggle_state(true,collapse_text) : companyname.accordion.collapse_toggle_state(false,collapse_text);
            });

            collapse_toggle.on('click',function(e){
                e.preventDefault();
                if(collapse_state) {
                    companyname.accordion.collapse(all_headings,all_contents);

                } else {
                    companyname.accordion.expand(all_headings,all_contents);
                }

                collapse_state = companyname.accordion.collapse_toggle_state(collapse_state,collapse_text);
            });

        },
        collapse : function(heading,content) {
            if(this.settings.animation) {
                content.slideUp(function () {
                    if (companyname.accordion.settings.jScrollPane) {
                        $('.scroll-pane').data('jsp').reinitialise();
                        $(window).trigger('resize'); //webkit fix for weird behavior on scroll
                    }
                });
            }else {
                content.hide();
                if (companyname.accordion.settings.jScrollPane){
                    $('.scroll-pane').data('jsp').reinitialise();
                    $(window).trigger('resize');
                }
            } 
            heading.addClass(this.settings.collapsed_class);
        },
        expand : function(heading,content) {
            if(this.settings.animation) {
                content.slideDown(function () {
                    if (companyname.accordion.settings.jScrollPane){
                        $('.scroll-pane').data('jsp').reinitialise();
                        $(window).trigger('resize');
                    }
                });
            } else {
                content.show();
                if (companyname.accordion.settings.jScrollPane){
                    $('.scroll-pane').data('jsp').reinitialise();
                    $(window).trigger('resize');
                }
            }
            heading.removeClass(this.settings.collapsed_class);
        },
        collapse_toggle_state : function(state,collapse_text){
            collapse_text.hide();
            (state) ? collapse_text.eq(1).show() : collapse_text.eq(0).show();
            return !state;
        }
    },

    tabs : {
        settings : {
            'buttons' : 'li.tab',
            'button_area' : 'div.tab-buttons',
            'content' : 'div.tab-content',
            'selected_class' : 'selected',
            'animation' : true
        },
        init : function(options) {
            this.settings = $.extend(this.settings,options);
            var settings = this.settings,
            buttons = $(settings.button_area).find(settings.buttons),
            content = $(settings.content);
            buttons.on('click',function(e){
                e.preventDefault();
                $this = $(this);
                $this.siblings().removeClass(settings.selected_class).end().addClass(settings.selected_class);
                $.get($this.find('a').prop('href'),function(data){
                    content.html(data); 
                });
            });

        }
    },
    menu : {
        item: null,
        timer: null,
        closing_timer: null,
        closing_item: null,
        current: null,
        selectors: {
            main_navigation: '.main-navigation',
            expanded_navigation: 'div.expanded-nav',
            breadcrumb: '.bread-crumb',
            social_media: '.social-media',
            nav_with_separator: '.category-navigation.type-2',
            categories: '.category-wrapper',
            category_icon: '.category-thumb',
            category_content: '.category-content'
        },
        init : function(){

            var self = this,
                expanded_nav = $(self.selectors.expanded_navigation);

            $(self.selectors.nav_with_separator).each(function(){

                var self = $(this),
                    parent = self.parent();

                parent.css({'display':'block','visibility':'hidden'});

                var sep = self.find('.sep'),
                    cols = self.find('.col'),
                    cMax = [];

                // Alignment fix
                cols.each(function(){
                    var i = 1;
                    $(this).children(companyname.menu.selectors.categories).each(function() {
                        if (!cMax[i])
                            cMax[i] = [];
                        cMax[i].push($(this).height());
                        $(this).attr('data-row',i);
                        i++;
                    });
                });
                for (var j=1; j<cMax.length; j++) {
                    $(companyname.menu.selectors.categories + '[data-row=' + j + ']').css('height',companyname.helper.maxValue(cMax[j]));
                }

                // Define max height for columns has seperation
                var sMax = companyname.helper.maxHeight(sep);
                sep.each(function(){
                    $(this).css('height',sMax);
                });

                parent.css({'display':'none','visibility':'visible'});

            });

            //Menu size alignments
            var breadCrumbSpace = 960-$(self.selectors.social_media).width();
            $(self.selectors.breadcrumb).css('width', breadCrumbSpace);

            if ($(self.selectors.breadcrumb + ' > ul').height() > 35) {//Two line
                var totalWidth = 0;
                $(self.selectors.breadcrumb + ' > ul > li').each(function () {
                    totalWidth += $(this).outerWidth();
                    if (totalWidth > breadCrumbSpace) {
                        $(this).addClass('second-line');
                        return false;
                    }
                });
            }

            if (!Modernizr.touch) {

                expanded_nav.parents('li').hover(function(){
                    var parent = this;
                    self.item = $(this);

                    if (self.closing_item != null) {
                        if (self.closing_item.index() == self.item.index()) { //same item, do not hide
                            clearTimeout(self.closing_timer);
                        } else { //another item, hide previous item immediately
                            self.closing_item.find(self.selectors.expanded_navigation).stop(true, true).hide();
                            self.closing_item.removeClass('hover');
                        }
                    }

                    self.timer = setTimeout(function () {
                        self.item.addClass('hover');
                        if ($('.lte-ie8').index() == -1) {
                            self.item.find(self.selectors.expanded_navigation).stop(true, true).fadeIn(function(){
                                $(parent).find(self.selectors.expanded_navigation).find('a').eq(0).focus();
                            });
                        }
                        else {
                            // IE8 anti-aliasing font issue fix
                            self.item.find(self.selectors.expanded_navigation).fadeTo(400,0.99,function(){
                                $(parent).find(self.selectors.expanded_navigation).find('a').eq(0).focus();
                            });
                        }
                    },400);

                }, function () {
                    self.closing_item = $(this);

                    clearTimeout(self.timer);
                    self.closing_timer = setTimeout(function () {
                        self.closing_item.find(self.selectors.expanded_navigation).stop(true, true).fadeOut();
                        self.closing_item.removeClass('hover');
                    },800);
                });

                expanded_nav.parents('li').find('>a').on('focus',function(){
                    $(this).parents('li').addClass('hover');
                    $(this).parents('li').find(self.selectors.expanded_navigation).fadeIn();
                });

                expanded_nav.find('a:last').on('blur',function(){
                    $(this).parents('li').removeClass('hover');
                    expanded_nav.stop(true, true).fadeOut();
                });

                //Hyperlink highlighting
                $(self.selectors.expanded_navigation + ' ' +  self.selectors.categories).each(function() {
                    if ($(this).children(self.selectors.category_content).find('ul').index() != -1) { //category contains sublinks
                        $(this).children(self.selectors.category_icon).find('a').hover(function() {
                            $(this).closest(self.selectors.categories).children(companyname.menu.selectors.category_content).find('a:first').addClass('hover');
                        },function() {
                            $(this).closest(self.selectors.categories).find('a').removeClass('hover');
                        });
                    } else { //category contains description
                        $(this).find('a').hover(function() {
                            $(this).closest(self.selectors.categories).find('a').addClass('hover');
                        },function() {
                            $(this).closest(self.selectors.categories).find('a').removeClass('hover');
                        });
                    }
                });
            }

            else {
               // Trick to fix click event on iphone & ipad
               $("body").css("cursor","pointer");
                expanded_nav.bind("click",function(e){
                    e.stopPropagation();
                })
                expanded_nav.parents('li').find('> a').bind("click",function(e){
                    e.preventDefault();
                    e.stopPropagation();
                    self.item = $(this).parent();
                    if(self.current == this) {
                        if(!$(this).parents(self.selectors.breadcrumb).size()) {
                            self.item.removeClass('hover').find(self.selectors.expanded_navigation).fadeOut();
                            self.current = null;
                        }
                        else {
                            location.href = $(this).attr("href");
                        }
                    }
                    else {
                        self.current = this;
                        $(self.selectors.expanded_navigation+':visible').stop(true, true).fadeOut(function(){
                            $(this).parent('li').removeClass('hover');
                        });
                        self.item.addClass('hover').find(self.selectors.expanded_navigation).fadeIn();
                    }
                });

                $(document).bind("click",function(e){
                    $(self.selectors.expanded_navigation+':visible').stop(true, true).fadeOut(function(){
                        $(this).parent('li').removeClass('hover');
                        self.current = null;
                    });
                });
            }

        }
    },
    validate : {
        settings: {
            form : '#form',
            options : {}
        },
        init : function(options){
            this.settings = $.extend(true,this.settings,options);
            settings = this.settings;
            var _form = $(settings.form);

            _form.validate(settings.options);
            _form.find('a.button').not('.non-submit').on('click',function(e){
                e.preventDefault();
                _form.submit(); 
            });
            _form.find('.submitter').on('keypress',function(e) {
                e = e || window.event;
                keycode = e.keyCode || e.which;
                switch (keycode) {
                    // Enter
                    case 13:
                        _form.find('a.onclick').trigger('click');
                    break;
                }
            });

        }
    },
    form: {
        /*
         *  Helper functions for forms.
         *  
         *  toggle_all -> One checkbox to toggle all other checkbox.
         *  unit_change -> Helps to switch between unit types of a form group.
         *  input_styling -> Helps to improve visualization of radio buttons/checkboxes.
         *  
         */
        toggle_all: {
            selectors: {
                form_wrapper: '.toggler',
                switcher_input: '.toggle-all'
            },
            init: function (selectors) {
                companyname.form.toggle_all.selectors = $.extend(true,companyname.form.toggle_all.selectors,selectors);
                $(companyname.form.toggle_all.selectors.switcher_input).on('click',companyname.form.toggle_all.run);
            },
            run: function () {
                var inputs = $(this).parents(companyname.form.toggle_all.selectors.form_wrapper).find('input[type=checkbox]');
                if ($(this).is(':checked')) {
                    inputs.not(this).attr('checked', true);
                } else {
                    inputs.not(this).attr('checked', false);
                }
            }
        },
        unit_change: {
            selectors: {
                unit_changer: '.unit-changer',
                elements_to_change: '.unit-target',
                form_wrapper: '.unit-wrapper'
            },
            init: function (selectors) {
                companyname.form.unit_change.selectors = $.extend(true,companyname.form.unit_change.selectors,selectors);
                $(companyname.form.unit_change.selectors.unit_changer).on('click',companyname.form.unit_change.run);
            },
            run: function () {
                var _wrapper = $(this).parents(companyname.form.unit_change.selectors.form_wrapper);
                var _elements = _wrapper.find(companyname.form.unit_change.selectors.elements_to_change);
                var _unit_type = $('input[name='+$(companyname.form.unit_change.selectors.unit_changer).attr('name')+']:checked').val();
                _elements.each(function () {
                    $(this).text($(this).siblings('.'+_unit_type).val());
                });
            }
        }
    },
    image_gallery : {
        settings: {
            id : 'gallery-slider',
            thumb_class : 'gallery-thumb',
            selected_class : 'selected',
            show_image_class : 'big-image',
            loading_class : 'loading',
            full_size_class : 'full-size'
        },
        init : function(options){
            this.settings = $.extend(this.settings,options);
            settings = this.settings;

            var thumbs = $('.'+settings.thumb_class),
            big_image = $('.'+settings.show_image_class),
            full_size_link = $('.'+settings.full_size_class),
            first_image = thumbs.filter(':first');

            companyname.product.slider.init({
                id: settings.id
            }); 

            big_image.addClass(settings.loading_class);
            big_image.html($('<img />').attr('src',first_image.addClass(settings.selected_class).attr('href')));
            full_size_link.attr('href',first_image.attr('data-source'));

            thumbs.on('click',function(e){
                e.preventDefault();
                $this = $(this);
                thumbs.removeClass(settings.selected_class);
                $this.addClass(settings.selected_class);

                big_image.find('img').attr('src',$this.attr('href'));
                full_size_link.attr('href',$this.attr('data-source'));
4

1 に答える 1

5

What they're doing is implementing a namespace in JS. companyName is just a reference to a large anonymous object (your application scope)

You're free to arbitrarily add properties/methods to the end of that object.

Here's a more sensible explanation.

A function called init() usually implies an event that fires shortly after the owning object is constructed. It occurs once and is usually reserved for initialization procedures.

head.ready("main", function() {
    setTimeout(function () {//FF 3.6 Fix
        sonypro.menu.init();
    }, 500);
});

^- This one is a little out of my full understanding. jQuery provides a ready event you can bind handlers to, but all the documentation I'm seeing only shows it with support for a single argument, which, if true, means that this is a custom handler implemented elsewhere in your code.

Normally, the format of that function is this:

selector.ready(function(){
//do some stuff when the selected element is ready
});

The ready event just assures that everything in your selector has been fully loaded before the code in the function you're passing executes (ie: images and such). Regardless, looks like your code is waiting a half a second after your page is ready, and then it's calling sonypro.menu.init();

于 2013-02-11T17:23:07.340 に答える