Skip to content

Instantly share code, notes, and snippets.

@tgvashworth
Last active December 15, 2015 05:09
Show Gist options
  • Save tgvashworth/5206491 to your computer and use it in GitHub Desktop.
Save tgvashworth/5206491 to your computer and use it in GitHub Desktop.
/**
* Sandbox
*
* Use Backbone Events to create a generic event handler.
* http://backbonejs.org/#Events
*/
define([], function () {
return {
create: function (parent) {
var sandbox = _.clone(Backbone.Events);
// ==================================
// Allow users of the sandbox to request a 'provided' piece of data.
//
// Takes an string identifier and a callback, which will be called with
// the provided value or undefined if no provider for that identifier
// is found.
//
// There can only be one provider for a given identifier.
// ==================================
sandbox.request = function (identifier, cb) {
if (!this._providers) this._providers = {};
var provider = this._providers[identifier];
// Defer request upwards
if (!provider && parent) return parent.request(identifier, cb);
if (typeof provider === 'function') {
return provider(cb);
}
return cb(provider);
};
// ==================================
// Provide a piece of information to users of the sandbox either via a
// raw value or via a callback.
//
// Takes a string identifier and a provision, which is any kind of data.
// If the provision is a function is will be called and passed a callback
// which it should call with the provided data.
//
// There can only be one provider for a given identifier.
// ==================================
sandbox.provide = function (identifier, provision) {
if (!this._providers) this._providers = {};
this._providers[identifier] = provision;
};
sandbox.log = window.console.log.bind(console);
return sandbox;
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment