-
-
Save torgeir/6934278 to your computer and use it in GitHub Desktop.
require js factory
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
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 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
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