Backbone / RequireJS and several models

I am having problems with mind transfer primarily RequireJS. I see that this is a good / necessary technology, but its implementation was real for me. I appreciate your help!

I am trying to develop a fairly flexible application with Backbone and RequireJS. The problem is that I'm completely used to the syntax, like new Person()without specifying dependencies. Is there an efficient way to use RequireJS with a lot of models? I think my problem always works with returns. I looked at using the factory method to create a model using a function require, but this requires the function to requirebe synchronous, which completely violates the RequireJS goal.

It just doesn't seem right to first require all my models, and then include those that are in the instantiation function, or am I?

Do you have any suggestions or tutorials on how to structure and model such an application?

Thanks for helping me!

Jmax

+5
source share
1 answer

You can use what I call the required js module template. If you know that a group of classes is often used together, you can do something like this.

First you define each class in a separate file, and then you define a module for storing them

Module.js

define([

    './models/FirstModel',
    './models/SecondModel',
    './views/FirstView',
    './views/SecondView',
    'txt!./templates/template.tpl'

], function(FirstModel, SecondModel, FirstView, SecondView, template) {

    return {
        FirstModel: FirstModel,
        SecondModel: SecondModel,
        FirstView: FirstView,
        SecondView: SecondView,
        template: template
    }

});

And then when you want to use the class from this module, you just do

define(['./Module'], function(Module) {

    var AView = Module.FirstView.extend({

        model: Module.FirstModel,

        render: function() {

            this.html(_.template(Module.template)(this.model.attributes));

            if (something) {

                this.$el.append(new Module.SecondView().render().el);
            }
        }
    })

    return AView;
});

, , requirejs, - .

- , , - / .. (, 2005!), :)

+21

All Articles