GeppettoJS / backbone.geppetto

Bring your Backbone applications to life with an event-driven Command framework.
http://geppettojs.github.com/backbone.geppetto/
MIT License
203 stars 28 forks source link

Mapping your Model within the Context #7

Closed chrisguselle closed 11 years ago

chrisguselle commented 11 years ago

Hi, I am coming to Geppetto from a Robotlegs background. In my Robotlegs apps I used to map my models to my contexts using something like injector.mapSingleton(MyModel); which I would add within my context file and then have access to everywhere.

I am setting up a very large javascript app where I would like my model to exist within a separate js file but be accessible through my context. What would you recommend to be the best way to do this using Geppetto. Your example app seems to just define the model with the context file itself.

Thanks in advance.

geekdave commented 11 years ago

Hi Chris. Glad to see another fellow Robotlegs developer here! I actually just thought about your question last night as I was working on a port of TodoMVC to illustrate how Geppetto would work in a more real-world app (the widgets example is pretty contrived).

The solution I came up with was:

models/fooModel.js:

define(["backbone"], function(Backbone) {
    var MyModel = Backbone.Model.extend({
        // your custom model stuff here
    };

    // create and return an instance of the model as part of the AMD definition,
    // effectively creating a sort of "singleton".  Whenever any other component
    // asks for this model definition, they will get this instance.
    return new MyModel();
});

FooContext.js:

define(["backbone", "geppetto", "models/fooModel"], function(Backbone, Geppetto, FooModel) {
    return Geppetto.Context.extend({
        // set the context's model to the already-instantiated 
        // pseudo-singleton that we created and returned in our model definition
        this.model = FooModel;
    });
}

Please let me know if this works for you. Some of the paradigms of Robotlegs don't map 1:1 with JavaScript, so I'm striving to find the closest match whenever possible that also makes sense from a design point of view.

Are you allowed to share the name of the company/project that this large app is for?

Thanks for the question! Dave

geekdave commented 11 years ago

Closing. @chrisguselle, please let me know if the above suggestion worked for you.

chrisguselle commented 11 years ago

Hi Dave,

Yes this is closer to my familiar way of working. Thanks for the suggestion - so far I like this approach.

Thanks again for sharing this project!