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