Note that there are some explanatory texts on larger screens.

plurals
  1. PObackbone.js view renders before model fetch
    primarykey
    data
    text
    <p>I'm trying to make a small backbone.js app, but struggle with the order of things.</p> <p>In my html file, I have two script blocks in the header:</p> <pre><code>&lt;script type="text/template" id="model-template"&gt; &lt;a href="#"&gt;&lt;%= title %&gt;&lt;/a&gt; &lt;/script&gt; &lt;script type="text/javascript"&gt; jQuery(function(){ window.model.fetch(); }); &lt;/script&gt; </code></pre> <p>In my app.js, I have defined a simple model, view and a router. </p> <pre><code>(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); </code></pre> <p>The application is served by a simple sinatra application. The url <code>/mymodel</code> serves a static json file:</p> <pre><code>{ "title": "My Model", } </code></pre> <p>When loading the application, I get an error in the javascript console: </p> <pre><code>Uncaught ReferenceError: title is not defined </code></pre> <p><strong>The problem seems to be, that the view renders itself before the model is fetched from the server. Why is that?</strong></p> <p>Yesterday, I followed the first two backbone.js screencasts from PeepCode. I have tried to compare my application with the one that came out of the screencasts, but cant't see a reason for why my application want work.</p> <p>Any suggestions? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload