It provides an implementation of several common messaging patterns , including an Event Aggregation Pattern , Command Pattern , and Observer Pattern .
These patterns make it easy to untie implementations to reduce object dependencies. Consider a simple βCombatβ game consisting of tanks and several targets. Without messaging templates, the tank must have explicit knowledge of the targets and how they work and cannot actually exist without the definition of target :
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 templates such as Observer, tank in the code above does not need to know your goals; rather, the goals themselves can determine 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 }); };
Chris camaratta
source share