Backbone.js - Model's attribute is not getting passed to view correctly -


i new backbone , trying understand why "title" not getting passed view , printing correctly. if create model title properties passes view , prints fine. pointer appreciated.

html:

$(document).ready(function(){ //model var appointment = backbone.model.extend({     urlroot : '/services/backbone'  // returns **{"title":"ms. kitty hairball treatment","cancelled":"false","id":"1"}**  }); var appointment = new appointment();  appointment.fetch({      success: function(response) {         console.log("successfully fetched : "+ response.attributes); // **prints undefine**     } });  console.log(appointment.attributes);  var appointmentview = backbone.view.extend({   render: function(){      $(this.el).html(this.model.get("title")); // **prints empty**     return this;   } });   //console.log(json.stringify(appointment.attributes)); //// initialize view model var appointmentview = new appointmentview({el: "#app-test", model: appointment});  appointmentview.render(); }); 

ok, asking few things, let's answer using code top bottom.

  1. not print properly

    success: function(response) {     console.log("successfully fetched : "+ response.attributes);  } 

the success callback takes few parameters, model, response , options. suspect first argument expect response {responsetext:"works"} etc, , second argument actual model. sure, log response see returned.

  1. console.log(appointment.attributes) should print out undefined because fetch() called earlier asynchronous, meaning line executed right after fetch(), did not wait fetch method finish.

  2. the appointment view prints empty should title. view initialed , render() called. there no guanrantee appointment fetched correctly. quick fix execute render function inside fetch success callback. this:

    var appointment = backbone.model.extend({     urlroot : '/services/backbone'  // returns **{"title":"ms. kitty hairball treatment","cancelled":"false","id":"1"}** }); var appointmentview = backbone.view.extend({     render: function(){         $(this.el).html(this.model.get("title"));          return this;     } }); var appointment = new appointment(); var appointmentview = new appointmentview({el: "#app-test", model: appointment}); appointment.fetch({     success: function(response) {         appointmentview.render();     } }); 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -