DCL

An elegant OOP with mixins + AOP for JavaScript.

Mixer

Mixer is a simple base class that mixes properties from its only argument directly on its instance. It can be used to add new properties, or override existing properties on an instance including methods. Mixer is very simple yet extremely powerful, when used correctly.

It can be included with following commands:

Include Mixer
1
2
3
4
5
6
7
8
9
10
11
12
13
// node.js
var Mixer = require("dcl/bases/Mixer");
...

// AMD (code)
require(["dcl/bases/Mixer"], function(Mixer){
  ...
});

// AMD (definition)
define(["dcl/bases/Mixer"], function(Mixer){
  ...
});

Description

Here is its definition:

Mixer
1
2
3
4
5
6
var Mixer = dcl(null, {
  declaredClass: "dcl/bases/Mixer",
  constructor: function(x){
      dcl.mix(this, x);
  }
});

As you can see that in a nutshell it is a one-liner that uses dcl.mix() to do the work. Mixer can be used as a base, or as a mixin, but usually it serves as the most deepest base to take care of parameters.

Refer to Best practices for constructors for discussion on constructor’ signatures.

Examples

Mixer example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var Person = dcl(Mixer, {
  declaredClass: "Person",
  firstName:  "",
  middleName: "",
  lastName:   ""
  constructor: function(){
    // no need to deal with parameters - they are already copied
    // on this instance by Mixer
    console.log("Hello " + this.firstName);
  },
  getFullName: function(){
    var name = [];
    if(this.firstName){
      name.push(this.firstName);
    }
    if(this.middleName){
      name.push(this.middleName);
    }
    if(this.lastName){
      name.push(this.lastName);
    }
    return name.join(" ");
  }
});

var bob = new Person({
  firstName:   "Robert",
  lastName:    "Smith",
  dateOfBirth: new Date(1985, 11, 31),
  shortName:   "Bob",
  getAge: function(){
    var today = new Date();
    // not really, just an estimate
    return today.getFullYear() -
      this.dateOfBirth.getFullYear();
  }
});

console.log(bob.getFullName() + " is " + bob.getAge());

Fork me on GitHub