【问题标题】:Json data from server not populating backbone model来自服务器的 Json 数据未填充主干模型
【发布时间】:2013-02-23 23:20:44
【问题描述】:

我是 Backbone.js 和 Require.js 的新手,我正在尝试从服务器获取数据并将其存储在我的骨干模型中。问题是数据没有填充模型。

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 ();
 });

模型

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

路由器

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

我检查了网络响应,我得到了“{video_id:1,video_name:test_backbone}”作为响应,但是当我 console.log (video.toJSON()) 我得到 - Object {id: "1Uw6ZkbsAH8",视频ID:“”,视频名称:“”}。我做错了什么?

【问题讨论】:

    标签: javascript backbone.js requirejs


    【解决方案1】:

    在调用fetch 后立即完成代码记录。 fetch 向服务器发出异步数据请求。即使在网络请求完成之前,您的日志调用也会立即执行。这是基于事件的编程的问题之一。

    尝试在success 回调中调用console.log

    video.fetch ( { 
        success: console.log(video.toJSON()); 
        } 
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多