0

试图获取数据但它没有填充模型,这就是我所拥有的

House = Backbone.Model.extend({
    urlRoot: 'http://localhost:3000/account/view/house',
    idAttribute: "_id",
    initialize: function(){
        this.on("create", function(){ console.log('Created house') })
    }
})

HousesCollection = Backbone.Collection.extend({
    model: House, 
    url: 'http://localhost:3000/account/view/houses'
})

housesCollection = new HousesCollection()

housesCollection.fetch() //to grab the json

//I actually go to network panel to see if it completes and it does then i try to show them


housesCollection.models // shows an empty array which means the pulled data didnt populate the models

如果我查看网络选项卡,我会看到它成功提取了正确的数据。

这是回应:

[
  {
    "__v": 0,
    "_id": "51e4a10f6357a5a015000004",
    "address": "17900 Opp",
    "buildingName": "S. End Build",
    "city": "NY",
    "modified_date": "2013-07-16T01:25:35.032Z",
    "creation_date": "2013-07-16T01:25:35.032Z"
  },
  {
    "buildingName": "North Building",
    "address": "17900 Kingslane",
    "city": "Detroit",
    "_id": "51e63f13f3924fa413000004",
    "__v": 0,
    "modified_date": "2013-07-17T06:52:03.670Z",
    "creation_date": "2013-07-17T06:52:03.670Z"
  }
]

知道为什么它不填充模型吗?

编辑:添加我的覆盖主干同步

APP.ajaxSettings = {
    "crossDomain": true
  , "xhrFields": {withCredentials:true}
  , "statusCode": { //Tell jQuery to watch for any 401 or 403 errors and handle them appropriately
        401: function(){console.log('401') },// Redirect the to the login page.
        403: function(){console.log('403') } // 403 -- Access denied
    }
}

APP.sync = Backbone.sync;
Backbone.sync = function(method, model, options) {
  // Update other options here.
    options = ORTO.ajaxSettings

    options.beforeSend = function (xhr) {
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    };

  APP.sync(method, model, options);
};
4

2 回答 2

0

当我应该扩展它时,我替换了选项

APP.sync = Backbone.sync;
Backbone.sync = function(method, model, options) {
  // Update other options here.

    //options = ORTO.ajaxSettings // this is wrong
    _.extend(options, ORTO.ajaxSettings)// this is right

    options.beforeSend = function (xhr) {
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    };

  APP.sync(method, model, options);
};
于 2013-07-19T20:58:49.653 回答
0

如果您收到响应并且可以成功地将您的模型视为 json 响应,则以下内容应该可以工作

var House = Backbone.Model.extend({
    urlRoot: 'http://localhost:3000/account/view/house',
    idAttribute: "_id"
})

var HousesCollection = Backbone.Collection.extend({
    model: House, 
    url: 'http://localhost:3000/account/view/houses'
})

var housesCollection = new HousesCollection(),
    req = housesCollection.fetch();

req.done(function() {
    console.log(housesCollection.models);
});

req.fail(function(jqXHR, textStatus, errorThrown) {
    console.log(jqXHR, textStatus, errorThrown);
});
于 2013-07-19T11:14:39.647 回答