Question

I have a backbone application which works fine but was getting a bit heavy to be in one file so I have started to separate it into different files I now have:

backbone-view.js
backbone-router.js
...

I am using my backbone router to instantiate views when the URL changes like so:

var Router = Backbone.Router.extend({
    routes: {
        'our-approach.php': 'instantiateOurApproach',
        'our-work.php': 'instantiateOurWork',
        'who-we-are.php': 'instantiateWhoWeAre',
        'social-stream.php': 'instantiateSocialStream',
        'contact.php': 'instantiateContact'
    },
    instantiateOurApproach: function() {
        if(window.our_approach_view == null) {
            window.our_approach_view = new OurApproachView();
        }
    },

    instantiateOurWork: function() {
        if(window.our_work_view == null) {
            window.our_work_view = new OurWorkView();
        }
    },

    instantiateWhoWeAre: function() {
        if(window.who_we_are_view == null) {
            window.who_we_are_view = new WhoWeAreView();
        }
    },

    instantiateSocialStream: function() {
        if(window.social_stream_view == null) {
            window.social_stream_view = new SocialStreamView();
        }
    },

    instantiateContact: function() {
        if(window.contact_view == null) {
            window.contact_view = new ContactView();
        }

    }
});

The problem I am now having is that I cannot access the views as they are declared in a separate file so the following are all undefined:

OurApproachView()
OurWorkView()
WhoWeAreView()
SocialStreamView()
ContactView()

I have tried doing:

window.OurApproachView()

But this doesn't work.

I am not sure what my next move is so if anyone can help that would be awesome.

Thanks!

EDIT

OK so it seems doing:

window.OurApproachView()

does actually work, my apologies there, but does anyone have a better suggestion?

Was it helpful?

Solution

You can take this approach:

// sample-view.js

var app = app || {};

$(function() {
    app.SampleView = Backbone.View.extend({
        el: '#sample-element',

        template : // your template

        events: {
        // your events      
        },

        initialize: function() {
            // do stuff on initialize
        },

        render: function() {
         // do stuff on render
        }
    });
}); 

Similarly, all your js files (models, collections, routers) can be setup like this. You would then be able to access any view from the router by doing:

var view = new app.SampleView();

OTHER TIPS

This works:

window.our_work_view = new window.OurApproachView();

But I don't like it as a solution.

Anyone suggest anything better?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top