Skip to Content

CSS3 flipping effect

Written on May 4, 2013 at 10:18 am, by

As you know because of the SIMD nature of the GPU it’s extremely good for graphical calculations. Since HTML5 and CSS3 are here we have a couple of ways for efficient and smooth animations one of them are the CSS3 transitions.

Before few days I needed a CSS3 flipping effect which should works at least in IE10, Chrome 25+ and Firefox. I tried different demos which I found in the web but there were couple of issues with them. The lack of support of preserve-3d in IE10 was one major thing, issues with backface-visibility in Chrome were also a bit frustrating. It looks like Firefox was the champion in the CSS3 flipping effects because most of the demos were failing in IE10 or Chrome but working on Firefox.

Anyway here is demo of the example I wrote:

Here is the CSS:

You can see that it’s extremely simple – just rotating the front and back panes with difference 180 degrees when the user hover the panel.

The HTML is even simpler:

And of course, there’s no JavaScript. You just don’t need it.

I hope that it was useful.

Why I should use publish/subscribe in JavaScript

Written on April 24, 2013 at 6:30 pm, by

This post is inspired by my answer at StackOverflow.

So why we should use publish/subscribe? Why it is useful? Is it making our work harder or it makes our application better?

And the answer…

It’s all about loose coupling and single responsibility, which goes hand to hand with MV* (MVC/MVP/MVVM) patterns in JavaScript which are very modern in the last few years.

Loose coupling is an Object-oriented principle in which each component of the system knows it’s responsibility and don’t care about the other components (or at least tries to not care about them as much as possible). Loosing coupling is a good thing because you can easily reuse the different modules. You’re not coupled with the interfaces of other modules. Using publish/subscribe you’re only coupled with the publish/subscribe interface which is not a big deal – just two methods. So if you decide to reuse a module in different project you can just copy and paste it and it’ll probably work or at least you won’t need much effort to make it work.

As talking about loose coupling we should mention the separation of concerns. If you’re building an application using MV* architectural pattern you have always a Model(s) and a View(s). The Model is the business part of the application. You can reuse it in different applications, so it’s not a good idea to couple it with the View of a single application, where you want to show it, because usually in the different applications you have different views. So it’s a good idea to use publish/subscribe for the Model-View communication. When your Model changes it publish an event, the View catch it and update itself. You don’t have any overhead from the publish/subscribe, it helps you for the decoupling. In the same manner you can keep your application logic into the Controller for example (MVVM, MVP it’s not exactly a Controller) and keep the View as simple as possible. When your View changes (or the user click on something, for example) it just publish a new event, the Controller catch it and decides what to do. If you are familiar with the MVC pattern or with MVVM in the Microsoft technologies (WPF/Silverlight) you can think for the publish/subscribe like the Observer pattern. This approach is used in frameworks like Backbone.js, Knockout.js (MVVM).

Here is an example:

Another example. If you don’t like the MV* approach you can use something a little different (there’s an intersection between the one I’ll describe next and the last mentioned). Just structure your application in different modules. For example look at Twitter.

If you look at the interface you simply have different boxes. You can think of each box as different module. For example you can post a tweet. This action requires update of few modules. Firstly it has to update your profile data (upper left box) but it also has to update your timeline. Of course, you can keep references to both modules and update them separately using their public interface but it’s easier (and better) to just publish an event. This will make the modification of your application easier because of loosing coupling. If you develop new module which depends on new tweets you can just subscribe to the “publish-tweet” event and handle it. This approach is very useful and can make your application very decoupled. You can reuse your modules very easy.

Here is a basic example of the last approach (this is not original twitter code it’s just a sample by me):

For this approach there’s very good talk by Nicholas Zakas. For the first MV* approach the best articles and books, I know, are published by Addy Osmani.

Drawbacks. You have to be careful about the excessive use of publish/subscribe. If you’ve got hundreds of events it can become very confusing to manage all of them. You may also have collisions if you’re not using namespacing (or not using it in the right way). An advanced implementation of mediator which looks much like an publish/subscribe can be found here https://github.com/ajacksified/Mediator.js. It has namespacing and feature like event “bubbling” which, of course, can be interrupted. Another drawback of the publish/subscribe is the hard unit testing, it may become difficult to isolate the different functions in the modules and test them independently.

Practical programming with JavaScript

Written on April 24, 2013 at 6:00 pm, by

Before few months I was invited by Telerik Academy to make a talk about JavaScript. Last Monday Marian Kostadinov, Radoslav Georgiev and me made a whole seminar about the topic. I’m addicted to the Object-Oriented programming so I choose to talk about that. You can find my slides at http://blog.mgechev.com/slides/javascript-patterns and a video (in Bulgarian) bellow in the post:

It was quite exciting for me to speak about this topic in front of about 200 people. The most amazing thing was that all of them were listening and were interested about JavaScript. I hope that it was useful seminar and all of use learned something new.

As short demo of the modular architecture, we discussed, I showed plainvm. I made some kind of “Inception” by embedding Windows 7 in my slide in which I opened browser with the same slides and after that played a little Mortal Kombat in the “virtual browser”. For me it was great experience I hope that I was interesting and useful. If you find any mistakes in my talk please tell me about them I’ll correct them in future.

JavaScript, the weird parts

Written on February 22, 2013 at 2:43 pm, by

To say that JavaScript is becoming more and more popular is such a typical and boring way to start such an awesome post…Anyway, JavaScript is becoming more and more popular each day…There’s client-side JavaScript with awesome API, you can do whatever you wish with it – write 3D games, stream video and audio, process files…There’s also a server-side JavaScript which is also awesome (I guess awesome will be a common word for this post). JavaScript is exiting language with big expressiveness power. It is object-oriented with many functional elements. It has prototype-based inheritance but if you wish you can implement inheritance in at least three different ways, which have countless subtypes…

But with the big power it comes the big responsibilities…For people who are new to the language, new to the functional and prototype paradigms, it’s very hard to understand in depth the language itself, especially if they have used primary Java, C#…or PHP…In this post we won’t talk about the strange things for the developers who are new to JavaScript. In this post we’ll talk about strange things in the language’s syntax and semantics. So, let’s begin!

Immediately-Invoked Function Expression

This is not uncommon thing in the language (we’ll look at far more strange things…) but I decided to include it because I haven’t met it in another languages and it has few interesting sides. That’s the common syntax for these functions:

There are few more variations, for example using the “dog balls” syntax:

or function expression:

Or…

or…

Or (last one, I promise):

The first strange thing here is that:

will work but:

Gives: SyntaxError: Unexpected token )

These functions are very useful and very common for the language, anyway, it looks a bit strange at first look…especially when we use:

And yes the use of ; is a good practice when you create plugins, for example. It’s useful to tell the interpreter explicitly that you are starting a new statement. Imagine that you’ve developed a new plugin and developer wants to use it in her project. As you know the semicolons in JavaScript are optional, so she might has something like:

That’s code that do nothing but declare a single function named foo. If we add the plugin we get:

This will invoke the foo function with single argument the returned result from the IIFE and cause unexpected results (alert foo in this case). Putting ; before your IIFE declaration will solve the problem.

Parentheses position matters

As we speak for functions…Let’s look at the return statement and the object literals:

So what do you mean, the object type is not equals to itself or what?! Actually nope, the first function foo returns undefined…And yes, that’s because we’ve put the open parentheses on new line. The return statement “does not see” that it has something to return (; are optional in JavaScript) so it returns nothing…The second function, bar, acts as expected because in the same line where is the return statement we have {. The return statement “knows” that there begins declaration of new object literal which it should return so that’s why the returned types are different…

That’s one of the reasons the codding style in JavaScript to points out that it’s good practice to put the opening parentheses on the current line.

Typeof null

One common mistake is:

And what happens if obj is null? TypeError: Cannot read property ‘prop’ of null. Yes, null is object and we have to be careful about that fact. You can modify the upper code in few ways, for example:

Equal is not always equal

Let’s look at this situation:

this is absolutely usual thing – one is equal to one and foo is foo. The array [1,2,3] is not equal to [1,2,3] because it’s simply a reference type. That’s common for most languages. But what if we:

Wow, true again?! Yeah…it’s true and there’s even a logical reason for that…Let’s look at the string representation of new Array(3):

JavaScript implicitely converts the values in the both sides of the == operator to strings and compares them. This is one more thing we should be careful for. Instead of == it’s better to use ===. Three times equal will check also the type of the operands:

Sum of objects and arrays

That’s my favorite topic! When we try to use operation with typical operands numbers, with operands which type is not number we usually get NaN.

All is as expected, the last example shows simple string concatenation. If we use:

we get NaN as expected ({} is an object literal). If we try to sum two empty arrays…

Pretty strange, right? Here the + is concatenation again…We concatenate two empty strings and we get an empty string. But what happens if:

We get [object Object] which is {}.toString(). That’s strange…

We know that the plus is commutative operation but the third example shows as that it’s not always true.

I think that this is one of the strangest things I described since the beginning of the post…With these strange properties we can do even stranger things, for example:

+!+[] is absolutely valid JavaScript syntax. Before I explain what happens first I must mention that undefined, , ” are all false in JavaScript. So now the explanation… As we saw [] + [] is “”, so we might think for [] as for “”. As I mentioned “” is false so !”" is true. The prefix plus converts the boolean value to numer, so +true === 1. With this approach we can get some text like:

This is valid and executable code in JavaScript, you can try it in your console. There are few small projects which translates text to these characters, for example translate.js and siggoscript.

But the strange things don’t stop here…

“Functional arithmetic”

Look at this expression:

This is one more valid and executable JavaScript code and once again it’s “strangeness” is connected with the implicit conversion to string:

Final words

These are few of the strange things of JavaScript’s syntax and semantics. Few of them can be dangerous in our daily work so we should be careful, another are funny and good to know but all of them are awesome! :-)

Functional programming with JavaScript

Written on January 21, 2013 at 10:28 am, by

This article is about the functional concepts of JavaScript. Some of them are built-in the languages, others extra implemented but all of them are very common for purely functional languages like Haskell. First I want to tell what I mean with the term purely functional language. These languages are “safe”, they will not make side effect i.e. evaluating an expression won’t change something in the internal state and lead to different result of the same expression when called next time. It seems very strange and useless to “imperative” guys like me, but actually there’s a list of benefits:

  1. Concurrency. We won’t have deadlocks or race conditions simply because we won’t need locks – the data is immutable. It starts to look very promising…
  2. Unit testing. We can write unit tests without worry about the state simply because there’s no such thing. We should care only about the arguments of the functions we test.
  3. Debugging. Simple stack trace is absolutely enough.
  4. Solid theoretical base. Functional languages are based on the lambda calculus which is a formal system. This theoretical foundation makes the prove of correctness of the programs very straightforward (for example using induction).

I hope these arguments are enough for you to look at the next sections. Now I’ll describe the functional elements in JavaScript and also provide implementations of aspects which are not native but their implementation won’t cost us much.

Anonymous functions

It seems that the functional programming becomes more and more popular. Even in Java 8 we’re going to have anonymous functions, in C# we have them since a long time. The anonymous function is a function which is defined without being bound to an identifier. JavaScript is familiar with this concept. If you’ve used JavaScript for more than simple exercises I’m sure that you’re familiar with them. When you use jQuery that’s probably one of the first things you type:

The function passed to $(document).ready is exactly an anonymous function. This concept give as great benefits some times especially when we want to keep things DRY.

More about passing functions in the next section…

High-order functions

High-order functions are functions which accepts functions as arguments or returns functions. We can return and pass functions as arguments in C#, Java 8, Python, Perl, Ruby… The most popular language – JavaScript has these functional elements built-in for a long time. Here is a basic example:

In the code above we have function called animate. It accepts as arguments property which should be animated, duration and a callback which should be invoked when the animation is completed. We have this pattern also in jQuery. There are plenty of jQuery methods which accept functions as arguments, for example $.get:

Callbacks are everywhere in JavaScript, they are just perfect for asynchronous programming like event handling, ajax requests, clients handling (Node.js) and so on. As I mentioned above you can avoid repeating yourself by using callbacks. They are extremely useful when you want a piece of your code to behave differently based on condition.

We have one more type of high-order functions – ones that return functions. There are many cases in JavaScript when returning a function is great approach. For example when we want to use caching:

We have a variable cache defined in the local scope of the parent function. In each call first will be checked whether the function have been already called with these arguments, if so the result will be returned immediately, otherwise the result will be cached and returned. Even the suggestion that the function will return the same result if it’s called with the same arguments is extremely functional way of thinking…

Imagine we have this case:

We have function called bar which accepts a single argument – baz and returns the sum of baz and the global foo. When we use memo we make bar cacheable and save a reference to the cacheable copy in the variable cached. When we call cached for first time its being evaluated for first time with argument 1 so it’s body is invoked and the result is 2. After that we increment foo and call the cached again. Now we get the same result (as we must in the pure functional languages) but it’s not the correct one. That’s because we have some kind of state. The state is something which will be considered lately in the Monads section (not the same type of state). Now lets keep our focus on the high-order functions and especially these which return functions.

Closures

Let’s look at memo again. We have variable called cache which is defined in the lexical scope of the function which returns the cacheable function. This variable is also accessible from the returned function because a closure is created. This is one more element from the functional programming. It’s very wide spread. One of the ways we can implement privacy in JavaScript is using closures:

In the example above we have object called timeline. It’s the result of the Immediately-Invoked Function Expression (IIFE) which returns an object with properties getArticles and setArticles which is the actual public interface of timeline. Inside of the lexical scope of the IIFE there’s definition of the articles array and sort function, which cannot be called directly using the timeline object.

I’ll end the topic about the high-order functions with ECMAScript 5. Along the years JavaScript gets even more functional elements. One of the things which appear first in our minds when we hear something about functional programming is the map function. It accept as arguments an anonymous function and a list. It applies the function to all elements from the list. map is officially part of ECMAScript 5.

Here is a basic usage of it:

In the code above map doubles the array. map is not the only function which is so typical for the functional programming languages and added to ECMAScript 5, there are also filter and reduce.

Recursion

Another element which is common for almost all modern programming languages is the recursion. It’s function which calls itself inside it’s body:

Above there’s a basic example which shows implementation of factorial using recursion. This concept is very popular so I’ll skip more detailed description.

Managing the state (Monads)

Of course, as we saw in the example with memorization, JavaScript is not purely functional language (probably that’s one of the reasons that the language is so popular…) because it has mutable data and states. Usually the purely functional programming languages like Haskell manages states using monads. There are implementations of Monads in JavaScript. For example here’s one by Douglas Crockford:

Here is a short demo which shows how we can create an I/O monad:

Anyway, for me using monads in JavaScript looks more like academical exercise than really useful but if we want to work in purely functional manner we can use them.

Schönfinkelization (or simply Curring)

Schönfinkelization is a functional transformation which allows as to fill function’s arguments step by step. When the function accept it’s last argument it returns a result. It was originated by Moses Schönfinkel and later re-discovered by Haskell Curry. Here is a sample implementation in JavaScript, by Stoyan Stefanov:

This is basic example using function for solving a quadratic equation:

If we want to fill the function’s arguments one by one we use:

This has practical application in some cases. Imagine you have a session object. The session key can be generated using complex time-expensive algorithm, it’s generation is required once the user visit our web site. Our session object also should store some kind of information about the user, for example current skin of the web page chosen by the client. Using currying you can call the session generating function, with it’s parameters, once the page load, this will produce the key. After that we can call the function for the user skin. This will produce the session object after the user select a skin but we won’t have overhead because of the complex algorithm which have generated the session key generation (it won’t be sensible by the user).

Pattern matching

One of the coolest things I’ve met in the functional programming is the pattern matching. Actually, if I have to be honest I’m not completely sure why I love it so much, probably because of it’s simplicity and the way it breaks the problem into smaller pieces. For example in Haskell you can define factorial like this:

It looks pretty cool. You divide a large task to smaller ones and make your solution simpler. When I started to write this article I’ve got an idea to implement something like this in JavaScript but I found out that it’s already implemented. Here is an example from Bram Stein’s funcy:

We have special variable for parameters which is inside fun – fun.parameter. When we call fact with – function () { return 1; } will be called, otherwise function (n) { return n * fact(n – 1); }. So cool, right?

I hope that I showed you clear enough all the functional aspects of JavaScript and how beautiful and simple they could be.