What are Javascript "mixins"?

Asked

Viewed 2,611 times

11

What are "mixins"?

I see in some Javascript codes and would like to know what it is; real examples of use.

2 answers

11


Javascript mixin is a class designed with a focus on DRY. It gives the developer the ability to take shortcuts to solve problems, almost like the famous "helpers", with the difference that a mixin may or may not reference or be referenced by a module1 without the direct need for extension or inheritance.

A practical and useful example

Buttons (<button>) and anchors (<a>) are conceptually components of GIFT, which means that when/if we speak of "components", we are going into business synthesis; going into the most generic layer of elements that our favorite markup language works on.

In a whole, components are rendering materials; they are items that when marked in your HTML have the ability to invoke for user view and interface materialization.

Therefore, I exemplified mixin in this scenario, through Javascript. Using buttons and anchors still, I developed the following objects:

var Button = {
    design: {
        colors: {
            background: 'blue',
            text: 'yellow'
        },
        borderRadius: 3,
        padding: 5,
    },
    shape: function () {
        return '<button style="background-color:' + this.design.colors.background + ';'
                + 'border-radius:' + this.design.borderRadius + 'px;'
                + 'padding:' + this.design.padding + 'px;'
                + 'color:' + this.design.colors.text + ';'
                + 'border: none;">'
                + this.getContent()
                + '</button>';
    }
};

and

var Anchor =  {
    design: {
        color: 'green',
        underline: true
    },
    destination: 'google.com',
    shape: function () {
        return '<a style="color:' + this.design.color + ';'
                + 'text-decoration:' + (this.design.underline ? 'underline' : 'none') + ';" '
                + 'href="http://' + this.destination + '">'
                + this.getContent()
                + '</a>';
    }
};

They have characteristics in common, right? design and shape are examples. However, if you pay attention, they are differentiated by their implementation; by their particular characteristics. In other words, each of these "components" has its own personality, like the marking itself, which in the case of the button is <button> and in the case of the anchor is <a>.

Recalling...

Remember I spoke earlier about "rendering"? Yes, components like these should have the ability to manifest themselves in the GIFT. Then we would do to teach the two objects (Button and Anchor) to project themselves without falling into the repetition of creating equal methods in their scopes? Mixins!

Look at this third object I drew:

var Component = {
    render: function (platform) {
        $(platform).html(this.shape());
    },
    append: function (platform) {
        $(platform).append(this.shape());
    },
    setContent: function (content) {
        this.content = content;
        return this;
    },
    getContent: function () {
        return this.content;
    }
};

It, in turn, has features that can make our buttons and anchors useful - and we can use it freely by cloning its scope between our two objects.

For cloning, in turn, I used the method extend() of Underscore.js:

_.extend(Anchor, Component);
_.extend(Button, Component);

The result became simple. To render our components, we would then do the following:

Button
    .setContent('Register')
    .append('body');

Anchor
    .setContent('And here if you already have an account!')
    .append('body');

If we put it all together, the result will be this:

var Component = {
    render: function (platform) {
        $(platform).html(this.shape());
    },
    append: function (platform) {
        $(platform).append(this.shape());
    },
    setContent: function (content) {
        this.content = content;
        return this;
    },
    getContent: function () {
        return this.content;
    }
};

var Button = {
    design: {
        colors: {
            background: 'blue',
            text: 'yellow'
        },
        borderRadius: 3,
        padding: 5,
    },
    shape: function () {
        return '<button style="background-color:' + this.design.colors.background + ';'
                + 'border-radius:' + this.design.borderRadius + 'px;'
                + 'padding:' + this.design.padding + 'px;'
                + 'color:' + this.design.colors.text + ';'
                + 'border: none;">'
                + this.getContent()
                + '</button>';
    }
};

var Anchor =  {
    design: {
        color: 'green',
        underline: true
    },
    destination: 'google.com',
    shape: function () {
        return '<a style="color:' + this.design.color + ';'
                + 'text-decoration:' + (this.design.underline ? 'underline' : 'none') + ';" '
                + 'href="http://' + this.destination + '">'
                + this.getContent()
                + '</a>';
    }
};

_.extend(Anchor, Component);
_.extend(Button, Component);

Button
    .setContent('Register')
    .append('body');

Anchor
    .setContent('And here if you already have an account!')
    .append('body');

To play and practice, here is jsFiddle.


1: a living class of your application written in/with Javascript;

  • I understood William, it was clear, ah and I saw the posts of his blog kkk two quoting me already kkk, I’m half-minded by performance, and I’m studying and analyzing in SPA with some frameworks, rsrs thanks, hug

5

Mixins is a very common term in object-oriented programming languages, in javascript the Mootools library being perhaps the best reference.

The basic idea behind the creation and use of mixins is the DRY concept which means "Don’t Repeat Yourself" - "don’t repeat yourself".

A mixin is for example an object where it defines functions/methods that can then be imported into other objects, namespaces or classes. If you have some methods in your code that are accurate in different parts of code, you can change these methods into a separate object and import/mix them (mixin) into your objects. So when you need to fix that code pad you just have to do it in one place.

Here’s an example of using Mixin in Mootools Classes: Source: Keetologi, Mark Keeto, one of the founders of Mootools

var Ringer = new Class({

    sound: 'ring.ogg',

    ring: function(sound){
        sound = sound || this.sound;
        new Sound(sound).play();
    }

});

var Phone = new Class({

    Implements: Ringer,

    initialize: function(number){
        this.number = number;
        this.sound = 'phone.ogg';
    },

    call: function(from){
        this.ring();
        new Notification('Call from ' + this.from);
    }

});

var AlarmClock = new Class({

    Implements: Ringer,

    initialize: function(alarmTime){
        this.time = alarmTime;
        this.sound = 'alarm.ogg';
    },

    alarm: function(time){
        if (time == this.time) {
            this.ring();
            new Notification('Wake up sleepy head!');
        }
    }

});

In this example above, both the "Phone" and "Alarm" classes have common code. The best solution, in order to place exactly the same code within each Class, is to make a Class apart and then import it into the Classes in which it is needed. In Mootools this method of importing "Mixins" is called "Implement".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.