1

I am new to Backbone.js and Require.js I am trying to get data from the server and store it in my backbone model. The problem is the data is not populating the model.

require.config({
paths:{
    jquery:"libs/jquery-1.7.1.min",
    underscore:"libs/underscore-min",
    backbone:"libs/backbone-min",
    models:"models",
    views:"views",
    collections:"collections"
},
shim:{
    "backbone":{
        "deps":["underscore","jquery"],
        "exports":"Backbone"
         },
        "underscore":{
             "exports":"_"
        }
     }
   });


 require (['routes'],function() {
      new Router ();
 });

The Model

define (['jquery','underscore','backbone'],function($,_,Backbone){
Video = Backbone.Model.extend ({
    defaults:{
        video_id:'',
        video_name:'',
    },
    urlRoot:"/video",
});
});//end define

The Router

define(['backbone','models/Video'],function(Backbone){
 Router = Backbone.Router.extend({
    routes:{
        "/":"index",
    },
    initialize:function (){
        this.index ();
    },
    index:function ()
    {
        video = new Video ({id:"1Uw6ZkbsAH8"});
        video.fetch();
        console.log (video.toJSON());
    }
 }); 
});//end define

I check the network response and I am getting "{video_id:1,video_name:test_backbone}" as a response but when I console.log (video.toJSON()) i get - Object {id: "1Uw6ZkbsAH8", video_id: "", video_name: ""}. What am I doing wrong?

4

1 に答える 1

2

in your code logging is done right after the fetch is called. fetch makes an asycnhronous request to server for data. Your logging call is executed right away even before the network request is completed. this is one of the gotchas of event-based programming.

try calling console.log in the success callback.

video.fetch ( { 
    success: console.log(video.toJSON()); 
    } 
);
于 2013-02-24T00:02:21.817 に答える