It provides implementations of several common messaging patterns, including the Event Aggregator Pattern, Command Pattern, and Observer Pattern.
These patterns facilitate decoupling of implementations to reduce object dependencies. Consider a simple "Combat" style game consisting of a tank and several targets. Without messaging patterns, the tank needs to have explicit knowledge about the targets and how they work, and in fact cannot exist without the target
definition:
var Tank = function(targets) { this.targets = targets };
Tank.prototype.fire = function() {
var self = this,
HpLoss = -500;
_.each(this.targets, function(target) {
if (self.isNear(target.coordinates) && target.canWithstand(HpLoss)) {
target.die();
}
}
var target1 = new Target(coordinatesA, armorA);
var target2 = new Target(coordinatesB, armorB);
var tank = new Tank([target1, target2]);
Using messaging patterns such as Observer, tank
in the code above doesn't need knowledge of its targets; rather, the targets can determine for themselves whether they should die:
var Target = function() {}
Target.prototype.calculateDamage = function(coordinates, damage) {
if (this.isNear(coordinates) && !this.canWithstand(damage)) {
this.die();
}
}
var Tank = function() {};
Tank.prototype.fire = function() {
this.trigger('fire', { damage: 400, coordinates: this.location });
};
// Now Tank is entirely self-contained, and some external mediator can
// make things happen at will:
function main() {
var target1 = new Target(coordinatesA, armorA);
var target2 = new Target(coordinatesB, armorB);
var tank = new Tank();
target1.listenTo(tank, 'fire', target1.calculateDamage, target1);
target2.listenTo(tank, 'fire', target2.calculateDamage, target2);
tank.fire();
var target3 = new Target3(coordinatesB, armorB);
target3.listenTo(tank, 'fire', target3.calculateDamage, target3);
}