Skip to content

Instantly share code, notes, and snippets.

@torgeir torgeir/demo.js forked from gnab/demo.js
Last active Oct 7, 2017

Embed
What would you like to do?
require js factory
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
You can’t perform that action at this time.