I am trying to make a small backbone.js application, but am struggling with the order of things.
In my html file, I have two script blocks in the header:
<script type="text/template" id="model-template"> <a href="#"><%= title %></a> </script> <script type="text/javascript"> jQuery(function(){ window.model.fetch(); }); </script>
In my app.js app, I defined a simple model, view, and router.
(function($) { window.MyModel = Backbone.Model.extend({ url: '/mymodel' }); window.mymodel = new MyModel(); $(document).ready(function() { window.MyModelView = Backbone.View.extend({ template: _.template($('#mymodel-template').html()), initialize: function () { _.bindAll(this, 'render'); }, render: function () { var renderedContent = this.template(this.model.toJSON()); $(this.el).html(renderedContent); return this; } }); }); window.MyApp = Backbone.Router.extend({ routes: { '': 'home' }, initialize: function () { this.myModelView = new MyModelView({ model: window.mymodel }); }, home: function() { var $body = $('body'); $body.empty(); $body.append(this.myModelView.render().el); } }); $(function() { window.App = new MyApp(); Backbone.history.start({pushState: true}); }); })(jQuery);
The application is served by a simple sinatra application. The URL /mymodel
is for a static json file:
{ "title": "My Model", }
When loading the application, I get an error message in the javascript console:
Uncaught ReferenceError: title is not defined
The problem is that the view is displayed before the model is retrieved from the server. Why is this?
Yesterday I ran the first two backbone.js scripts from PeepCode. I tried to compare my application with the one that came out of the screencasts, but cannot explain the reason why my application wants to work.
Any suggestions?
Vegar source share