Created
October 11, 2013 13:05
-
-
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.
This file contains 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
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} |
This file contains 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
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