marcus
marcus

Reputation: 10096

Create require js plugin that listens for a backbone js global event

Is it possible to create a require js plugin that listens for a backbone global event and if that event is fired require js kicks in?

This is the scenario I would like to reproduce with require js http://jsfiddle.net/u2aej/

I'm thinking that this would look something like this.

require(['views/SubModule', 'editorLoaded!'], function (SubModule, editorLoaded) {
    //This function is called once the Editor is loaded.
    var view = new SubModule({el: '#sub-view' });
});

I'm not so familiar with require so maybe I'm totally wrong about this but I would like to here from you if you think this is a good idea and if it's possible?

Upvotes: 0

Views: 268

Answers (1)

Paul Grime
Paul Grime

Reputation: 15104

It might be simpler to decouple the module from the event, and load the module explicitly using require().

Borrowing from this answer for Backbone global events - Backbone.js global events. Create the vent:

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

vent.trigger("some:event");

Then load the module when the event is fired:

vent.on("some:event", function(){
    require(["myModule"], function(myModule) {
        myModule.doItsThing();
    });
});

But if you do want to write a plugin, then the best example to follow is probably - https://github.com/requirejs/domReady/blob/master/domReady.js.

Take a look at that, and replace with a version that calls the callbacks when a particular global event is fired, rather than when the DOM is ready.

However, I suspect that your dependency would look like this:

require(["globalEvent!editorLoaded"], function() { ... });

rather than this:

require(["editorLoaded!"], function() { ... });

(assuming your plugin is called globalEvent)

See the text plugin, https://github.com/requirejs/text, for how to pass parameters to the plugin.

Upvotes: 1

Related Questions