underscore.js - backbone.js 'undefined' get request -


this code:

$(function (){ var slide = backbone.model.extend({     defaults: {         castid  :1,         id      :1     },     urlroot:  function(){         return 'slidecasts/' + this.get("castid") + '/slides/';     }, });   var slideview = backbone.view.extend({     el: $("#presentation"),     events: {         'click #next': 'next',         'click #previous': 'previous',     },     initialize: function(){         _.bindall(this, 'render', 'next');         this.model.bind('change', this.render);         this.render();     },     render: function(){         this.model.fetch();         var variables = {              presentation_name: "this slide-number: ",             slidenumber: "xxx",             imageurl:  this.model.url() +"/"+ this.model.get('imagelinks'),              slide_content:  this.model.get("content")};         var template = _.template( $("#slide_template").html(), variables );         this.$el.html( template );         return this;     },     next: function(){         console.log(this.model.id);         this.model.nextslide();     },     previous: function(){         console.log("previous function in view");     } });  testslide = new slide(); var slideview = new slideview({model: testslide});  }); 

this works fine in debug console see request "slidecasts/1/slides/1/undefined" of course fails. don't understand trigger request.

edit - template code

<script type="text/template" id="slide_template">   <label>presentation <%= presentation_name %>  </label> <br/>   <img src="<%= imageurl %>" id="slide_pic" /> <br/>   <textarea id="slide_content">     <%= slide_content %>   </textarea>   <div id="next">next slide </div>   <div id="previous">previous slide </div>   </script> 

you have asynchronous problem.

this sequence of events:

  1. you call this.model.fetch() populate model.
  2. you variables.imageurl = this.model.url() + '/' + this.model.get('imagelinks').
  3. the (asynchronous) fetch hasn't returned yet this.model.get('imagelinks') undefined.
  4. you build html , use this.$el.html(template) update page.
  5. the browser renders html using incorrect imageurl 2.
  6. a bad request logged because of 5.
  7. the fetch 1 returns server , triggers 'change' event.
  8. the 'change' event triggers new call render.
  9. this render call has populated this.model variables.imageurl correct , html comes out right time.

if let fetch trigger render problem go away:

initialize: function(){     _.bindall(this, 'render', 'next');     this.model.bind('change', this.render);     this.model.fetch(); }, render: function() {     // before except no this.model.fetch() } 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -