开发者

Unexpected behavior in my code

I have the following code:

var myApp = {
  Models: {},
  Views:  {},
  Collections: {},
  Controllers: {},
  init: function() {
    new this.Controllers.Main();
    Backbone.history.start();
  }
}

myApp.Models.User = Backbone.Model.extend({
  idAttribute : '_id',
  url         : 'currentUser',
  initialize  : function() {
    this.fetch();
  }
});

myApp.Controllers.Main = Backbone.Controller.extend({
  initialize: function() {
    this.currentUser = new myApp.Models.U开发者_如何学Goser();
  },
  routes: {
    ''            : 'index',
  },
  index: function() {
    console.log('index called');
    console.log(this.currentUser);                 // shows the correct object
    console.log(this.currentUser.attributes);      // empty object ?
    console.log(this.currentUser.toJSON());        // empty object ?
    console.log(this.currentUser.get('name'));     // undefined ?
  }
});

$(function() {
  myApp.init();
});

What am i missing ?


This is an asynchronous problem. Fetch is doing an asynchronous Ajax call, it will return but no values will be set yet. Do something like that:

this.currentUser.bind("change:id", function(){
  //your console logs
});

When the fetch succeed and an id is set on the model, the logs will be called.


If you do new myApp.Models.User(); , you create a new empty User .. How could it have attributes ..

You didn't specify an id so how could it be fetched from the server ?

And you didn't specify defaults values ..

So it seems coherent to me, no ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜