Question

I am writing a Backbone application using RequireJS for defining modules. I have reached the age old problem of how to pass around the event aggregator without using globals or passing it as a parameter into every single View.

vent = _.extend({}, Backbone.Events);

I have taken the approach used here for Marionette, but since I'm not using Marionette (yet), I've adapted it to use the boring old vent object:

vent.js:

define(['underscore', 'backbone'], function (_, Backbone) {
    return _.extend({}, Backbone.Events);
});

So now in my various modules, I can publish and subscribe, like:

enquiry-list-view.js:

define(['backbone', 'vent'], function (Backbone, vent) {

    var EnquiryListView = Backbone.View.extend({

        events: {
            'click .enquiry-list-item-manage': 'manageClick'
        },

        manageClick: function () {
            vent.trigger('navigate', 'enquiry/' + id);
        }
    });
});

app-router.js:

define(['backbone', 'vent'], function (Backbone, vent) {

    var AppRouter = Backbone.Router.extend({
        routes: {
            'enquiry/:id': 'enquiryManage'
        },

        initialize: function () {
            //listen out for navigate events
            this.listenTo(vent, 'navigate', this.gotoRoute);
        },

        gotoRoute: function (route) {
            this.navigate(route, { trigger: true });
        }
    });

This pattern seems to work okay, the router can listen to the vent object and the view can trigger an event on it.

But... how are the router and view both looking at the same object? Doesn't return _.extend({}, Backbone.Events); in vent.js always return a new object every time it is required by a different module?

Is there something about RequireJS that I'm not getting, or is _.extend doing something to Backbone.Events, or is there perhaps something (else) about JavaScript that I don't fully understand?

Was it helpful?

Solution

In AMD, define callback executes only ones. Its result is used in all dependent modules. Checkout this post. I think your question is related to it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top