Skip to content

Instantly share code, notes, and snippets.

@gnab
Created October 11, 2013 13:05
Show Gist options
  • Save gnab/6934267 to your computer and use it in GitHub Desktop.
Save gnab/6934267 to your computer and use it in GitHub Desktop.
RequireJS factory plugin. Uses temporarily unique resource names to trick Require into calling plugin#load every time the resource is needed, and returns a new instance of the resource every time.
define('itemFactory', function () {
function Item() {
this.value = Math.ceil(Math.random() * 1000);
};
return Item;
});
define('firstView', ['factory!itemFactory'], function (item) {
console.log('First view; ' + JSON.stringify(item));
});
define('secondView', ['factory!itemFactory'], function (item) {
console.log('Second view; ' + JSON.stringify(item));
});
// => First view; {"value":317}
// Second view; {"value":35}
define('factory', function () {
var count = 1;
return {
load: function (name, req, onLoad, config) {
var cap = name.match(/^\d+!(.*)$/);
if (cap) {
name = cap[1];
}
req([name], function (factory) {
onLoad(new factory());
});
},
normalize: function (name, normalize) {
if (!name.match(/^\d+!/)) {
return (count++) + '!' + name;
}
return name;
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment