问题
I am receiving JSON from the server which looks like
{
"accountType": ["Full","Trial"],
"states": [
{"state":"AL","stateDescription":"Alabama","featured":"A1"},
{"state":"AK","stateDescription":"Alaska","featured":"B1"}
],
"dates":[
{"dateDescription":"Jan","month":1,"year":2008},
{"dateDescription":"Feb","month":2,"year":2008}
]
}
In the Backbone file I'm doing:
define([ 'backbone', 'underscore', 'vent', ], function (Backbone, _, vent) {
'use strict';
return Backbone.Model.extend({
url: {},
loaded: false,
defaults: {
accountType: [],
states: [],
dates: [],
},
initialize: function () {
this.on('change', this.change);
var that = this;
$.getJSON("webapp/jsondata", function (data) {
that.set({
states: data.states.state,
});
});
$.getJSON("webapp/jsondata", function (data) {
that.set({
dates: data.dates.dateDescription,
});
});
$.getJSON("webapp/jsondata", function (data) {
that.set({
accountType: data.accountType,
});
});
},
});
});
So each $.getJSON should get the relevant data and populate the backbone model defaults.
Except at the moment only the account type works. I don't understand why this would work and the others wouldn't as it's the same code. The only difference is in the JSON data, accountType has 2 pieces of data. States has 3 and I only want to return one piece of this (state).
So I guess my issue is in specifying the data being retrieved in the $.getJSON code but many hours online have not revealed an answer.
回答1:
Your states and dates keys in your data are arrays, but you try to access them as hashes.
If you want to extract the state keys from your states array, you can use _.pluck :
$.getJSON("webapp/jsondata", function (data) {
that.set({
states: _.pluck(data.states, 'state')
});
});
With the data given, _.pluck(data.states, 'state') will give you ["AL", "AK"]
Not that, as written, your model could be greatly simplified by using model.fetch with model.parse. For example :
return Backbone.Model.extend({
url: "webapp/jsondata",
loaded: false,
defaults: function () {
return {
accountType: [],
states: [],
dates: [],
};
},
parse: function (data) {
return {
accountType: data.accountType,
states: _.pluck(data.states, 'state'),
dates: _.pluck(data.dates, 'dateDescription')
};
},
initialize: function () {
this.on('change', this.change);
this.fetch();
},
});
And beware using arrays in a defaults hash, use a function instead.
来源:https://stackoverflow.com/questions/22226223/populating-data-from-json-for-drop-downs