Question

What are the main benefits backbone.wreqr has over a js object, both cases having access to marionette's Event aggregator.
Wouldn't assigning/calling methods from an object work the same way as Commands / RequestResponse. To me i see no need to implement this other than giving semantic/readability a +1.

https://github.com/marionettejs/backbone.wreqr
Can someone please enlighten me, this is my first backbone (and modular) application.

Was it helpful?

Solution

The benefits are:

  • event and command handling is optional and you don't need to check manually yourself for undefineds
  • optionally multiple handlers for each event
  • lazy execution of commands (fire event first, register command later and it will immediately be executed)
  • you can define the scope of execution w/o using any additional methods like $.proxy, ...

OTHER TIPS

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top