jdev
jdev

Reputation: 589

How to create Backbone View in a separate js file

I'm trying to understand how to modularize the Backbone ToDo tutorial

Originally everything is inside the same file, but if I try to extract to another file:

var TodoView = Backbone.View.extend({
    ...
});

then this throws an error:

var view = new TodoView({model: todo});

**Uncaught TypeError: undefined is not a function**

It's probably due to a scope issue, but I don't know how to create a reference inside the $(function() so I can create this new object inside the main function.

Upvotes: 2

Views: 967

Answers (3)

ssohjiro
ssohjiro

Reputation: 72

Assuming that your first code part is TodoView.js, and your second code part is app.js.

Write your html file like this,

<html>
    <head>
        <script type="text/javascript" src="js/TodoView.js"></script>
        <script type="text/javascript" src="js/app.js"></script>
    </head>
    <body>
        // your dom
    </body>
</html>

(Edited, at 2015-07-27)

sorry for my late reply. how about this?

<html>
    <head></head>
    <body>
        <!-- your dom -->

        <script type="text/javascript" src="js/TodoView.js"></script>
        <script type="text/javascript" src="js/app.js"></script>
    </body>
</html>

In many case, most javascript codes are appended to just before </body>, so that javascript can use your dom!

Upvotes: 2

jdev
jdev

Reputation: 589

Ok, the solution was to move the script references to the end of the body instead of inside the head tags.

I think that the reason is that TodoView.js is making use of templates that were defined in the body, and since the js file was being loaded before the body, the templates were not yet available.

Upvotes: 0

tribe84
tribe84

Reputation: 5632

You can use something like require.js to load your external files and manage dependancies.

Upvotes: 0

Related Questions