Monday, April 20, 2015

Mixins for JavaScript Classes

The same code in several places is the pain. Today I will say a few words about repeated parts of classes. Coders had invented a solution of this problem a long time ago: you can move similar methods and properties to a common parent class or, if you don’t have one, you can use mixins. There are many implementations of this pattern in JavaScript, but I want to review the case when a mixin is placed to the prototype chain.

Picture of Idea

Let’s start with visual presentation of the problem. Consider we have two base classes and two child classes inherited respectively.

At one point of development process, similar functionality is required in both the child classes. A dull copy-paste will look on the scheme like that

It’s very often, the functionality has nothing to do with the base classes, therefore, to move it to another parent class is improperly and inconvenient at least. So let’s place it to a special entity - mixin. In the context of the language mixin can be a simple object.

Now we are about to most interesting question, that is “What’s the right way to mix our mixin to the classes?” From a personal perspective I can assert that the best way is creation of temporary classes with the mixin as a prototype and insertion them into the prototype chains.


Saturday, February 7, 2015

How to refactor spaghetti without getting depressed

using the Backbone.View.Elements library

It’s not yet another post about slick and sexy code architecture you can achieve using React, Angular or what’s now in vogue? The article is about situation when you have pile of jQuery spaghetti wrapped to Backbone views. Sounds familiar?

The problem #1: poorly expressive selectors

All of us know spaghetti in JavaScript is reflection of malformed HTML templates. Therefore, most likely such the code contains some tricky ambiguous DOM transformations and manipulations. It’s very hard to comprehend it because you need to keep in mind a lot of indistinct names of elements while you are trying to find out what’s going on in general. Let’s give expression to our code:
_selectors: function () {
    return {
        elemName: '.block__elem-name'
    };
}
Move selectors to one place and give understandable names to elements which will be retrieved by them. Now we can search elements of the view like this
this._elem('elemName');
instead of
this.$('.block__elem-name');
Not bad? Let’s go ahead!