Monthly Archives: April 2013

Quick Introduction to Backbone.js

Backbone.js is a very light JavaScript framework, which brings more structure and a MVC (Model-View-Controller) approach into your code. Let’s just jump right in, shall we?

Alright. Let’s create a Model.

var Game = Backbone.Model.extend({
    initialize: function() {
        // constructor
    },
    defaults: {
        name: 'default title',
        releaseDate: 2000
    },
    getFancyReleaseDate: function() {
        return 'This game was released in ' + this.get('releaseDate');
    }
});

We have now extended the Backbone.Model array with our new ‘Game’ model. We can create instances of it like that:

var LeagueOfLegendsModel = new Game({
    id: 1,
    name: 'League of Legends',
    releaseDate: 2009
});

Models can have events. These events are incredibly powerful if you are working with Views. We’ll jump into that later, let’s first bind a ‘change’ event to our new model instance:

LeagueOfLegendsModel.on('change', function(game) {
    console.log(game.get('name') + ' changed!');
});

Every time an attribute of ‘LeagueOfLegendsModel’ changes, this function gets triggered. Sounds easy? It is.

We now want to put our model into the DOM. For that, we will use a View.

var GamesView = Backbone.View.extend({
    initialize: function() {
        this.listenTo(this.model, 'change', this.render);
    },

    render: function() {
        this.$el.html('').append(
            $('<p/>', {
                text: this.model.get('name')
            })
        ).append(
            $('<p/>', {
                text: this.model.getFancyReleaseDate()
            })
        );
    }
});

Of course we need to instantiate it:

var LeagueOfLegendsView = new GamesView({
    el: '#games',
    model: LeagueOfLegendsModel
});

‘el’ is in Backbone.js the place in the DOM where it should render. Since it uses jQuery, ‘$el’ is automatically a jQuery object. When we instantiated the view, we set an event listener onto the model ‘LeagueOfLegendsModel’. When the model changes, the view automatically gets rendered again, so your page always displays the newest information.

Of course there are way more things you can do with Backbone.js and Underscore.js, check out their documentations!

How to programmatically check if a Number is even: Multiple solutions

There are multiple ways to check if a number is even. Most people are using the Modulo Operator:

return (number % 2 == 0);

The modulo operator divides the number and returns the rest of the division. If we divide by 2 and the rest is 0, it’s obviously an even number. Now, the modulo operator is not very fast. In most languages we could also use this little trick:

return ((number / 2) * 2 == number);

If ‘number’ was, let’s say, 13, dividing by 2 would result in 6.5. Since it’s an integer, the .5 just gets cut off, leaving us a 6 behind. Multiplying 6 by 2 results in 12. 12 is not equal to the original number (13), therefore it returns false (number is odd).

That’s a lot faster than using the modulo operator. But we can do this even faster by using the Bitwise AND-Operator:

return !(number & 1);

With this operator, we can mask a number with bits and perform a bitwise AND operation. Lets take 13 again for an example. 13 in binary is this:

1101

The first bit represents 2^0. Every odd number has that bit set, so if we mask 13 with 1 we get this:

  1101
& 0001
  ____
  0001

If we would mask an even number like 12 with 1, we get this:

  1100
& 0001
  ____
  0000

Therefore, the output of (number & 1) is true if it’s odd. With the NOT-Operator we simply invert the boolean value and get a very fast isEven method. Here are some benchmarks in JavaScript (The last function does not work in JS, since it’s an implicit language):

Function Execution Time
isEvenBitwise 9.5016
isEvenModulo 37.2635
isEvenIntegerTrick 12.0399

(Firefox 20.0, Windows 7, 1e6 iterations)

Conclusion

In most cases, it doesn’t matter what method you are using. If you need speed, use the bitwise AND-operator. If you need readability, use the modulo operator.

Easily create prettier select Elements with stylishdropdown.js

I recently wanted to style some select tags with CSS. Well, let’s just say that it didn’t work out the way I expected it, so I wrote a little jQuery plugin which automatically creates pretty HTML select fields. Check out the code and a demo on GitHub.

jQuery('select').stylishDropdown();

You can also set the opening/closing speed of the dropdown by simply passing an integer to the plugin:

jQuery('select').stylishDropdown(300);

This opens and closes the element in 300ms.

You don’t like the blue colors? Why don’t you just change them with regular CSS:

.first-dropdown > .dropdown,
.first-dropdown > .dropdown > .arrow {
    background-color: #3C3C3C;
    color: #fff;
}

There are more things you can do, have a look at the demo.html file on GitHub. Here is a quick demonstration of it: