Skip to content

Instantly share code, notes, and snippets.

@mathiasverraes
Created October 29, 2012 08:47
Show Gist options
  • Save mathiasverraes/3972442 to your computer and use it in GitHub Desktop.
Save mathiasverraes/3972442 to your computer and use it in GitHub Desktop.
Javascript Dependency Injection using partial functions
// CommandHandler Class
var CommandHandler = function(repository) {
this.handle = function(command) {
// do stuff with repository and command
}
}
// Elsewhere, create an instance of the class...
var myCommandHandler = new CommandHandler(repository);
// ...and use it
myCommandHandler.handle(command);
var _ = require('lodash'); // Lodash is an API-compatible fork of Underscore.js
// The same as the first example, but as a class-less function
var handle = function(repository, command) {
// do stuff with repository and command
}
// Elsewhere, inject the repository by creating a partial
var handle = _.partial(handle, repository);
// ...and use it
handle(command);
var sum = function(a, b) {
return a + b;
}
var addFiveTo = partial(sum, 5);
sum(5, 10) // returns 15
addFiveTo(10) // returns 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment