More complex custom callback example

In a previous post I gave a basic example on how to create a simple callback function: http://webconfiguration.blogspot.co.uk/2012/10/javascript-creating-method-with.html

In this post I will demonstrate how to combine this simple callback example with a more complex function (i will use the sorting method i posted previously: http://webconfiguration.blogspot.co.uk/2012/10/javascript-sort-select-and-lists.html ) 

Step 1
Calling the method with the selectbox as the callback:

sortList(‘select#country’, function(obj){
      obj.selectbox();
});

Step 2
The sorting method running the function passed as a paramter, ie the callback:

/*ordering lists*/
    sortList: function(selector, callback) {
         /*varring up the object*/
        var selector_object = $(”+selector+”);
      
        /*hide the select whilst shuffling*/
        selector_object.hide();
      
        /*determin element type of*/
        switch ( selector_object.prop(‘tagName’)){
            case ‘UL’ : var childType = ‘li’;
            break;
            case ‘SELECT’ : var childType = ‘option’;
            break;
        }

        /*start the arrays*/
        var listElement = new Array();

        /*populate array of elements*/        $(”+selector+’ > ‘+childType+”).each(function(){
            var element = $(this).clone().wrap(‘

‘).parent().html();
            listElement.push({key: element, value: $(this).html() });
        })

        /*sort the object*/
        listElement.sort(function(a, b){
            if(a.value > b.value){
                return 1;
            }
            else if(a.value < b.value){
                return -1;
            }
            return 0;
        });

        /*empty the repopulate sorted*/
        selector_object.empty();
        $.each(listElement, function(a,b) {
            selector_object.append(b.key);
        });
      
        /*hide the select whilst shuffling*/
        selector_object.show();

        /*Check the callback param exists and is a function then run it*/
        if (callback && typeof(callback) === “function”) {
            callback(selector_object);
        } 
   }

Creating a method with a callback similar to jQuery in javascript

If you are familiar with jQuery then you might well be used to using the ‘callback’ feature of many of its methods. For example the fadeIn and fadeOut: Only running something after the element in question and completed its ‘fadeyness’.

Well it is not actually that hard to build your own call backs.

The ability to perform callback functions lies in JavaScript’s ability to pass one function to another as a parameter, eg:

myFirstCallback(‘string passed’, function(var){
    alert(var);
});

function myFirstCallBack(paramA, callback){
    alert(‘This is the first parameter:’ + paramA);

        /*Check paramB is a function then run it*/
        if (callback && typeof(callback) === “function”) {
            var returnVal = ‘This function has finished, you may now continue with what ever else you wanted to do’;
            callback(returnVal);
        }
}

Sort select and lists elements with javascript

NB: This function has been improved with a callback and is documented here

Have you ever found the need to order a select elements options or list elements at the client’s side?

Recently I was tasked with this: Due to the framework being used (eZ Publish and it’s native in-capabilities or creating a simple template operator with two parameters.

So, here is a javascript with jquery option to doing just that built with a callback function for when the said method has completed:

Step 1
Calling the method with the selectbox as the callback:

sortList(‘select#country’);

Step 2
The sorting method:

/*ordering lists*/
    sortList: function(selector) {
         /*varring up the object*/
        var selector_object = $(”+selector+”);
      
        /*hide the select whilst shuffling*/
        selector_object.hide();
      
        /*determin element type of*/
        switch ( selector_object.prop(‘tagName’)){
            case ‘UL’ : var childType = ‘li’;
            break;
            case ‘SELECT’ : var childType = ‘option’;
            break;
        }

        /*start the arrays*/
        var listElement = new Array();

        /*populate array of elements*/        $(”+selector+’ > ‘+childType+”).each(function(){
            var element = $(this).clone().wrap(‘

‘).parent().html();
            listElement.push({key: element, value: $(this).html() });
        })

        /*sort the object*/
        listElement.sort(function(a, b){
            if(a.value > b.value){
                return 1;
            }
            else if(a.value < b.value){
                return -1;
            }
            return 0;
        });

        /*empty the repopulate sorted*/
        selector_object.empty();
        $.each(listElement, function(a,b) {
            selector_object.append(b.key);
        });
      
        /*hide the select whilst shuffling*/
        selector_object.show();
       }

Sort an object in javascript

The native function sort() is pretty handy on a straight forward array. However if you array/ object gets a little more complex the you will need to make use of the function within the sort method

Example

console.log(arr);
/* console.log (js’s print_r) of an object (array) looks like*/

If we wanted to sort the object by the name parameter we could use a handy little native function called localeCompare

/* now console.log (js’s print_r) of an object (array) looks like*/

Modulus to test odd or even in javascript

I always seem to forget this tool and always have to look it up, I have no idea why… most likely because I really don’t have the chance to use it that often.

One of those common tools that’s easy to forget about is the Modulus operator (%), which returns the remainder of a division operation: If you divide some number by two, a remainder of 0 indicates an even number, while a remainder of 1 indicates an odd number.

var toolBox = {
    isEven: function(n){
        return (n%2 == 0) ? ‘even’ : ‘odd’;
    }
}

for(var n=0; n < rrData.length ; n++){
      var oddEvenClass = toolBox.isEven(n);
      var rrCont = $(‘

‘);

…}

Schedualed optimising


Optimizing tables is a little like sunday house clean… nobody really want to do it but it has to be done either way.

So, here is a little script that you can plug into cron to run once weekly at some god earthly time say 2am on a Sunday evening… the reason for the out of hours time slot is running OPTIMIZE will lock a table, and as you can imagine you don’t really want to be locking a table during operational hours.

This script will only optimize tables with more than 100Kb free space

Loading slider images via AJAX

Pre-loading content to be displayed later is bandwidth intensive for both your servers and your clients on slow internet connections.

However it seems that a lot of the picture sliders/ galleries seem to function in this way. Considering the number of visitors that will actually want to scroll through all the wonderful pictures and advertisements you have in your gallery… it might be worth considering AJAXing them in on doc ready.

So I was faced with fixing this problem the other day and this is the solution I produced.

Overview
1 – Only load first image correctly from server and the rest with ‘fake source’
2 – On document ready switch the ‘fake source’ to the true source for the images as they are needed (not all at one go).
TIP: When sending the “fake sources” from your server send them as full paths complete with http. Non-complete paths such as ‘var/some/path/to/images.jpg’ can sometimes resulting in the images not loading.

Step 1 Serverside
Ensure that only the first slide will arrive a your clients screen loaded with a correct image source and all the rest their sources stored in the image tag but in an alternative attribute.

EG:

Step 2 Client Side
Now when your document has loaded you could run a script similar to this:

            number = parseInt(number);
            var n = site.home_blocks.showcase_gallery.showcase_items;
           
            if( n != 0 ){
               
                var numbers = new Array;
               
                if(number == 0){
                    numbers[0] = n,
                    numbers[1] = number;
                    numbers[2] = number + 1;
                } else {
                    numbers[0] = number – 1,
                    numbers[1] = number;
                    numbers[2] = number + 1;
                }
               
                for (var i = 0; i < numbers.length; i++) {
                   
                    var image = $(‘.gallery-showcase-carousel-item:eq(‘+ numbers[i] +’) img’);
           
                    if( image.attr(‘fakeSrc’) ){
                        /*building new image from scratch*/
                        var img = $(‘‘);
                        $(img).attr(‘width’, image.attr(‘width’));
                        $(img).attr(‘height’, image.attr(‘height’));
                        $(img).attr(‘title’, image.attr(‘title’));
                        $(img).attr(‘alt’, image.attr(‘alt’));
                        $(img).attr(‘style’, image.attr(‘style’));
                        $(img).attr(‘src’, image.attr(‘fakeSrc’));
                        /*inserting the new image after the fake image*/
                        $(image).after(img),
                        /*removing completely the old image*/
                        $(image).remove();
                    }
                }
            }

The above script does the following:
1 – recieves a number which refers to the slide currently being ‘slid’ to
2 – knows how many slides there are in the slider all together
3 – creates an array of the immediate sibling slide numbers and itself
4 – iterates through the said array building new images to replace the img tags with fakeSrc

(In theory you should be able to simple switch the fake source with the real src tag, however i found this to be sometimes a little buggy so simple rebuilt the image based information already there in the img tag)
 

Being object orientated in javascript

So you have figured out how to write all your PHP code in an object orientated fashion, you are reaping the benifits… well here is an simple guide on how to make you javascript object orientated as well. This is not essential but I find it easier to manage when things get big and complex.

Step 1 – Your first file to include
Obviously after you jQuery files and any other libraries and frameworks you use the next file to include in your head should contain this (name the var as you like but I prefer to name it the same as the domain name for the project)

var mydomain = {}

Step 2 –  Your first addon
In your next file you can add to the above var and include what ever function you need:

mydomain.toolkit = {
    init: function(){
       $(document).ready(function(){
            /*add some event listeners here*/
            $(‘#someID’).click(function(){
                 mydomain.toolkit.alertMe(this);
                });
       });
    },
 
   alertMe: function(obj){
     alert( $(this).html() );
   }
}
/*now kick this ‘object’ off*/
mydomain.toolkit.init();

This method is very expandable and really easy in assiting you to better organise you code, however you will need to read up on binding events to elements brought in via AJAX.

This post i wrote a while ago uses javascript namespacing in this fashion:
http://webconfiguration.blogspot.co.uk/2012/08/jquery-ui-date-picker-class.html

Finding the current dialect from an eZ Publish template

On of the clever aspects to eZ Publish that I do like is the ability to create a different dialect to form the site access for micro sites, mobile versions… and this just happens to be the neatest way of finding everything about the current language and dialect:

{def $locale = fetch( ‘content’, ‘locale’ )}

Where the dialect would be in:

{$locale.country_variation}

exit() safely in ezPublish whilst in PHP

From within modules eZ Publish uses standard PHP, as of course it is a framework built from PHP, however one of the functions you should really use php’s exit();

This is because of the fact that the framework also uses some Java scripts which may continues running even after PHP has exited.

You may want to print out some json_encoded information for example then kill your process.php in which ever module you are in. The following line will safely exit all running scrupts:

eZExecution::cleanExit();