Created
October 29, 2012 08:47
-
-
Save mathiasverraes/3972442 to your computer and use it in GitHub Desktop.
Javascript Dependency Injection using partial functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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