shino
shino

Reputation: 4734

How can I handle multiple activities in a Javascript single-page app?

For example, I might have a menu screen, an options screen, an editor screen, etc. Previously, I've wrapped each of these into a class an provided and activate and deactivate function for each one. The activate function would show the related dom element and start accepting input. The deactivate function would hide the related dom element and stop accepting input. So if the user was in the menu screen, and clicked on the "set options" button, I would do something like this:

this.deactivate() // We're currently in the menu, so the menu object is "this"
options.activate()

Is there a standard way of handling this scenario?

Upvotes: 1

Views: 138

Answers (1)

Bryan A
Bryan A

Reputation: 3634

There are many frameworks that implement what is largely called the "publish/subscribe" pattern in JavaScript; Backbone.Events is one that I use frequently. Here's a really simple way to implement it. This assumes that you're including both backbone.js and underscore.js in your project.

var Foo = {},
    Bar = {};

_.extend(Foo, Backbone.Events);
_.extend(Bar, Backbone.Events);

Foo.prototype.deactivate = function() {
    // Do stuff 
    this.trigger("Foo_Deactivated");
};

Bar.prototype.activate = function() {
    // Do stuff 
    this.trigger("Bar_Activated");
};

myFoo = new Foo();
myBar = new Bar();

myBar.on("Foo_Deactivate", function() { 
    this.activate(); 
    this.trigger("Bar_Activated"); 
}, this);

Hope that answers your question!

Upvotes: 1

Related Questions