Kevin Whitaker
Kevin Whitaker

Reputation: 13425

Require.js & Marionette: defining includes when extending classes

I'm working on a project using Require.js, Backbone and Marionette, and the define/function calls at the top of my files are getting a bit ludicrous. I'd like to find a way to move the "includes" out of the topmost define block, and into the extend where the are relevant.

So my structure roughly looks like this:

define(['underscore','jquery','handlebars','someTemplate','someModel',etc...], function(_,$,Handlebars,template,model,etc...){
  var someView = Backbone.Marionette.ItemView.extend({
    // code here
  });
  return someView;
});

So as I add more views to the file, that define list gets really, really, long. I've tried doing something like:

var someView = define(['someTemplate','someModel'], function(template, model){
  return Backbone.Marionette.ItemView.extend({
    // code here
  });
]);

But then someView is undefined when I call it later. Am I doing this wrong, or is it not possible?

Upvotes: 0

Views: 647

Answers (2)

danikoren
danikoren

Reputation: 4301

you can use your require.js config file dependencies shim to aggregate your "common" or needed modules into one namespace:

shim: {
       marionette: {
            deps: ["backbone", "json2", "bootstrap", "backboneRpc"],
            exports: 'Marionette'
        },

        flot_pie: {
            deps: ['jquery', 'charting', 'flot_resize'],
            exports: '$.plot'
        },
  }

so now you can call all you need like this:

define([
    'marionette',
    'flot_pie'
],

function(Marionette, graph) {

Upvotes: 2

Andreas Köberle
Andreas Köberle

Reputation: 110922

You should split your modules. Having a really long list of dependencies is a sign that your module does to much. Most of the time all view need is model or collection and maybe some subViews and the global eventbus.

Also think about the need to require jQuery,Backbone etc. This are stuff that you will need in most of your modules, its easier to combine them in one file and load them in the first place. There is no much advantage to require this files, all it does is cluttering your define section with a lot of boilerplate.

The define call btw. does not return anything thats why someView is undefined in example. If you really wanna go with this solution you have to use require when you use someView later on. But even then its much cleaner to put someView in its own module file.

Upvotes: 5

Related Questions