Saturday, 17 August 2013

RequireJS, Backbone, and AJAX: Loading/Storing JSON into a model on initialization

RequireJS, Backbone, and AJAX: Loading/Storing JSON into a model on
initialization

I recently just picked up RequireJS and Backbone and have run into trouble
loading JSON files. I can't figure out how to load then store a JSON
object (verified by console.log() output) into a model. The three or four
ways I've tried always result in the model attribute showing as undefined.
After loading and then calling model.set() I call console.log(this.model),
which shows that the data has been stored; however on the next line when I
write console.log(this.model.get('data')) I get an undefined error. This
persists when I call the same thing in render(). It seems like an async
logic error on my part?
I want to do something like the following:
// TableView.js
initialize: function(args) {
this.model = new TableModel();
var that = this;
d3.json(args.dataPath, function(err, d) {
that.model.set('data', d);
});
// console.log()'s were placed here
},
render: function () {
var data = this.model.get('data');
}
// Other.js
var tableView = new TableView('dataPath': 'pathOfAwesome');
tableView.render();
From a legibility standpoint I don't want to have render() called in a
callback within initialize(). Especially since the data I'm working with
can be filtered, and I'd rather have the render calls be explicit.
In the following Line 41 is this.model and Line 42 is this.model.get('data')
I also haven't figured out a good way to organize my code in
Backbone/Require yet, so stylistic/idiomatic input would also be much
appreciated :)

No comments:

Post a Comment