Xrender
Xrender

Reputation: 1445

Best way to store backbone views

I've built my first backbone app and really enjoying the structure that backbone provides. However I have found myself with some minor annoyances which I am sure others have found solutions for.

So currently I have created a file structure like

models
      index.js
      user.js
views
      index.js
      user.js

So in my 'index.js' in the views folder I currently have all of the views, so lets say I have

headerView
footerView
buttonView

etc etc

So I currently have multiple 'views' inside one generic 'view js file' related to one page app. Problem is its not intuitive to find a particular view, I open a editor and find the correct view.

In other MVC, I would store each view in its own unique file, and use them as appropriate - do other users do the same here? I guess my concern is having multiple separate js files? I use the minify project to minify the js anyway, so could create a group, but wondering what others have done?

Upvotes: 0

Views: 748

Answers (2)

SunnyRed
SunnyRed

Reputation: 3545

I would suggest that you take a look at require.js. Here is a tutorial that should get you started.

The core idea is sth. like the following.

  • each Model, View, Collection, Router, whatever resides in its own file and is called a module
  • at the top of each module you define its dependencies, meaning which other modules need to be loaded for your new module to work
  • require.js loads your dependencies and guarantees access via your self defined variables

Definiton (e.g childView.js)

define([
    'jQuery',
    'Underscore',
    'Backbone'
], function($, _, Backbone){
     return Backbone.View.extend({
         //your usual view methods and properties
     });
});

Reuse (e.g parentView.js)

define([
    'jQuery',
    'Underscore',
    'Backbone',
    'pathToChildView/childView.js'
], function($, _, Backbone, ChildView){
     return Backbone.View.extend({
         // your usual view methods and properties
         // + access to your ChildView Modul
     });
});

If you have trouble with the module loading syntax the sugared variant might be your friend.

Upvotes: 3

Moustachio
Moustachio

Reputation: 184

It pays to separate each object into a view/template pair in hierarchical folders for better navigation. You then simply construct the child object in the view and pass the el element. This way you can reuse each object throughout the project as needed.

Upvotes: 0

Related Questions