Backbone fetch()不会填充模型

时间:2013-07-19 04:43:44

标签: javascript backbone.js

尝试获取数据但不填充模型,这就是我所拥有的

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"
  }
]

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

编辑:添加我的overrode主干同步

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

2 个答案:

答案 0 :(得分: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);
});

答案 1 :(得分: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);
};