• Javascript variable scope and variable hoisting

    Lately I’ve been doing quite a bit of Javascript and today I’ve experienced an interesting problem. A function variable, which should be global, is logged to console. Then it is redefined as a local variable. You might assume, that the logged value would be the value of the global variable, but in such case you would be wrong, just as I was. In fact it was returning “undefined”.

    Sample code:

    var variable = 5;
    function attempt() {
        alert(variable);
        var variable = 6;
    }
    attempt();
    

    If you want to check it yourself, here’s a JSFiddle link.

    What’s happening???

    This is the so called “variable hoisting” in action. If you define a variable in a function, it doesn’t matter if it’s at the top or somewhere later in the function, it will be “hoisted” to the top, but it will not be initialized. That is where “undefined” comes from.

    While researching what happened I found Mozilla Developers Network, which has some great info on variable scope and hoisting.

    Such behavior is unexpected to traditionally trained programmers, that’s why Douglas Crockford in his book “Javascript: The Good Parts” recommends to define all variables at the top of the function.


  • Disable Flash automatic loading on Google Chrome - Flash On Demand

    If you’re on a bandwidth limited network, how many times have you wished you could stop that Youtube video from loading automatically on some random blog post? Flash applications on the web usually slow down the page load, which may be not very noticable on fast computers, but on slower ones it really is.

    What can we do about it and still be able to use Flash (for watching videos on Youtube, Vimeo and others, playing flash games on any game site and etc.)? One way would be to make Flash load on demand.

    By allowing Flash (and any other plugins for that matter, e.g. PDF) to load only on demand, we:

    • Save bandwidth (usually not much, but it’s still worth it)
    • Get a more responsive browser
    • Pages load faster

    So how do we do it?

    Setting Flash to load on demand

    1. Click on the Wrench image in top right corner
    2. Select Settings from the menu
    3. Scroll down and click on Show advanced settings
    4. Under Privacy section click on Content settings... button
    5. Scroll down and under Plug-ins section click on Click to play button
    6. You’re done!

    If you’ve done everything correctly, instead of a flash player, you should see a gray box with an image of a puzzle piece in the middle of it with text Click to run Flash.

    If you wish to load the Flash embed, just click on the box where it says Click to run Flash.


  • The Singleton Pattern - Design Patterns

    Singleton is a design pattern that restricts the instantiation of the class, usually to one object. It is useful when you need one instance throughout whole project, it may be used for Caching, Logging, Database and etc.

    For this example we’ll be doing just that - we’ll create a Logger class that allows for exactly one object.

    It is worth noting that there are two types of Singleton initialization: Lazy (initializes only when required) and Eager (initializes always). We’ll use only lazy initialization for this example.

    Logger class

    By default Singleton pattern requires a getInstance() method. We also need to add logs (log($message) method) and to get all logs (get_logs() method). For storage we’ll use a simple array.

    So far we’ll need these methods:

    • getInstance()
    • log($message)
    • get_logs()

    So let’s go.

    First, let’s define our base class with method definitions:

    <?php
    
    /**
     * Logger class
     * Singleton using lazy implementation
     */
    class Logger
    {
        private static $instance = NULL;
        private $logs;
    
        private function __construct() {}
        public function getInstance() {}
        public function log($message) {}
        public function get_logs() {}
    };
    

    Note that we made our __construct() method private. That is a part of the Singleton design pattern and that’s how we will be limiting instantiation of our Logger class.

    Next, let’s define __construct() method to set $logs to array():

    <?php
    private function __construct() {
        $this->logs = array();
    }
    

    Then we need to define getInstance() class. It needs to return $instance and instantiate itself if necessary.

    <?php
    public function getInstance() {
        // Instantiate itself if not instantiated
        if(self::$instance === NULL) {
            self::$instance = new Logger();
        }
        return self::$instance;
    }
    

    We’re almost there. Now let’s define our logging methods:

    <?php
    public function log($message) {
        if(!empty($message)) {
            $this->logs[] = $message;
        }
    }
    
    public function get_logs() {
        return $this->logs;
    }
    

    The completed class:

    <?php
    
    /**
     * Logger class
     * Singleton using lazy implementation
     */
    class Logger
    {
        private static $instance = NULL;
        private $logs;
    
        private function __construct() {
            $this->logs = array();
        }
    
        public function getInstance() {
            // Instantiate itself if not instantiated
            if(self::$instance === NULL) {
                self::$instance = new Logger();
            }
            return self::$instance;
        }
    
        public function log($message) {
            if(!empty($message)) {
                $this->logs[] = $message;
            }
        }
    
        public function get_logs() {
            return $this->logs;
        }
    };
    

    And lastly let’s create main.php that will test out our Logger class.

    <?php
    require 'Logger.php';
    
    $logger = Logger::getInstance();
    $logger->log('This is my first logged message!');
    print_r($logger->get_logs()); // Print out all logs
    
    // Let's use method chaining
    Logger::getInstance()->log('This is my second logged message!');
    print_r($Logger::getInstance()->get_logs());
    

    Now if you’d run main.php using php main.php command, you should get this output:

    Array
    (
        [0] => This is my first logged message!
    )
    Array
    (
        [0] => This is my first logged message!
        [1] => This is my second logged message!
    )
    

    If you do, you’re done! You’ve successfully implemented the Singleton pattern!

    I’ve created a pattern repository on GitHub where you can find this and other design patterns already implemented.


  • Enable Skype icon on Unity notification panel on Ubuntu 12.04 LTS

    When you do a fresh install of Ubuntu 12.04 (Or any version with Unity for that matter), you install Skype and expect it to work as it used to. But if you close the main window - you soon notice that Skype icon is not being displayed in top panel.

    To fix this you will need to run a few commands. So open up your terminal and run this:

    gsettings get com.canonical.Unity.Panel systray-whitelist
    

    You should get something like this:

    ['JavaEmbeddedFrame', 'Wine', 'Update-notifier']
    

    Basically this means, that Skype is not whitelisted, thus is not allowed by default to display its tray icon. We need to fix this. Append 'Skype' to the list so that you have something like this:

    ['JavaEmbeddedFrame', 'Wine', 'Update-notifier', 'Skype']
    

    Then wrap it with double quotes (”) and add gsettings set com.canonical.Unity.Panel systray-whitelist in front of it. At this point you should have something like this:

    gsettings set com.canonical.Unity.Panel systray-whitelist "['JavaEmbeddedFrame', 'Wine', 'Update-notifier', 'Skype']"
    

    Now just copy this to your Terminal and execute the command. Reboot afterwards. Now you should see the icon.


  • The Observer Pattern - Design Patterns

    Before we start, you might ask:

    What is a design pattern?

    Design pattern is a general solution to particular problem that is occurring commonly. However this is not an already implemented source code (you’ll have to do that yourself). It is not an already finished design either. You can incorporate design patterns into your application design.

    It formalizes best practices and describes interactions between objects and classes. Basically it is a template for how to solve a problem.

    If you want to get a better description of what a design pattern is, you can read about it on Wikipedia

    Observer pattern

    It is a one-to-many push type design pattern, in which an object (“Subject”) maintains a list of dependants (“observers”). Once the subject changes state, it automatically notifies each observer with its new state.

    You can think of it as a mailing list. Mailing list is the subject, you attach to it by sending in your e-mail address. But there can be many subscribers - Observer pattern does not limit the number of observers.

    When there is a new email, the state has changed and the server emails it to each of the subscribers, including you!

    Example

    Let’s build our own simple application that uses the Observer pattern. In this example we’re going to use PHP.

    There will be at least 2 classes - one for the Subject, one for the Observer.

    The Subject will have to have at least these three methods:

    • Attach - a method that the observers will use to register
    • Detach - observers may want to unregister
    • Notify - This will change subject’s state

    As for the Observer, we can get away with this single method:

    • Notify - Notification method, which will be called by the subject

    Ok, let’s start coding! Let’s start by creating a Subject class:

    <?php
    // Subject.php
    class Subject {
        private $observers = array(); // We will store observers here
    
        public function attach($observer) {
            if(!in_array($observer, $this->observers)) { // Make sure we don't add an observer twice
                $this->observers[] = $observer; // Add the observer
                return true;
            } else {
                return false; // Observer was not added
            }
        }
    
        public function detach($observer) {
            if(!in_array($observer, $this->observers)) { // Make sure the observer is registered
                return false;
            } else {
                $key = array_search($observer, $this->observers); // Find observer's key
                unset($this->observers[$key]); // Remove the observer
                $this->observers = array_values($this->observers); // Reindex the observer array, as unset leaves a gap
                return true;
            }
        }
    
        public function notify($message) {
            foreach($this->observers as $observer) { // Notify each observer
                $observer->notify($message); // Dispatch the message to each observer
            }
        }
    };
    

    Ok, we’ve implemented our Subject class. Observers will register through attach method and unregister through detach method. Notifications will be sent with notify method.

    Now let’s build our Observer class:

    <?php
    // Observer.php
    class Observer {
        public function notify($message) {
            echo "I have received a message: \r\n";
            var_dump($message); // Just print out any information it may contain: strings, numbers, objects...
            echo "END OF MESSAGE\r\n";
        }
    };
    

    Our Observer class only needs notify method, which will output all received messages.

    And lastly, let’s create our demo program that makes use of these classes:

    <?php
    // main.php
    require_once('Subject.php');
    require_once('Observer.php');
    
    $subject = new Subject(); // Create a Subject
    
    // Let's try to change state. It should not output anything as it doesn't have any observers registered
    $subject->notify('This shall not be read!');
    
    // Let's create an Observer, register it and send another notification
    $observer = new Observer(); // Create an Observer
    $subject->attach($observer); // Register Observer to the Subject
    $subject->notify('Can you see me?'); // Send notification to the Observer
    

    If we run this, we should see Can you see me? text. If you do - good work! Now you know the Observer pattern.

    I’ve created a Github repository with complete code from this article.