Reputation: 743
I created a Backbonejs model in a RequireJs module that way :
define(['model/newmodel']), function (Newmodel) {
var newmodel = new Newmodel();
}
I create a new module where I'd like to update my newmodel
define(['views/view']), function (View) {
// I'd like to modify some properties of the 'newmodel' object here
}
Do you have an idea ?
Upvotes: 0
Views: 37
Reputation: 35790
David Sulc's approach is certainly one way to go, but you absolutely can pass instance around in Require if you have a good reason to. In general it makes more sense to pass around classes, but if you have a "global-ish" object it might make sense to pass it directly.
First off I'd start by getting your capitalization consistent: it's pretty universal practice to name classes with capital letters, and instances with lower-case ones, which would make you rename your "newmodel" file/module to "Newmodel:
define(['model/Newmodel']), function (Newmodel) {
var newmodel = new Newmodel();
}
With that out of the way you can make your "newmodel" (lower-case) file/module return the instance itself:
define(['model/Newmodel']), function (Newmodel) { var newmodel = new Newmodel(); return newmodel; }
Once you've done that your view can do whatever it wants to that instance by bringing it in normally through require:
define(['model/newmodel', 'views/view']), function (newmodel, View) {
// I'd like to modify some properties of the 'newmodel' object here
modifyPropertiesOf(newmodel)
}
Upvotes: 0
Reputation: 25994
You probably want to do this instead:
define(['model/newmodel', 'views/view']), function (NewModel, View) {
var newmodel = new Newmodel();
var myView = new View({
model: newmodel
});
}
You usually use requireJS to make sure "classes" are loaded when your code needs them, not to pass around instances.
Upvotes: 1