Wednesday, January 11, 2012

Problems with Accessing Attributes from a Backbone.js Model


I have a JSON File looking like this:



JSON :




{
"clefs": [
{"title": "..", "path": ".."},
... ,
{"title": "..", "path": ".."}
],

....

"rests": [
{"title": "..", "path": ".."},
... ,
{"title": "..", "path": ".."}
]

}



This is a nested JSON, right? So I try to convert that into Model/Collections nested into Backbone.js like this:



Backbone.js :




window.initModel = Backbone.Model.extend({
defaults: {
"title": "",
"path": ""
}
});

window.CustomCollection = Backbone.Collection.extend({
model: initModel
});

window.Init = Backbone.Model.extend({
url : function(){
return "/api/data.json"
},

parse: function(response) {

clefs = new CustomCollection();
clefs.add(response.clefs);
this.set({clefs: clefs});

.....

rests = new CustomCollection();
rests.add(response.rests);
this.set({rests: rests});
}
});



Now I came out with a Model and into its Attributes my Collection: clefs, ..., rests.



When it's come to pass my Collection to a View I cannot!



I made this



View :




$(document).ready(function() {
var AppRouter = Backbone.Router.extend({
routes: {
"" : "init"
},

init: function(){
this.init = new Init();

//this.init.attributes return the Collections: clefs, ..., rests into an object(firebug)

this.initView = new InitView({collection: this.init.get("rests") });//dont work
//this.initView = new InitView({collection: this.init.get(rests) });//dont work
//this.initView = new InitView({collection: this.init.attributes });//dont work
//this.initView = new InitView({collection: this.init.attributes['clefs'] });//dont work
this.init.fetch();

}
});

var app = new AppRouter();
Backbone.history.start();
});



It's an ugly situation right now!! I have a Backbone Model with Attributes(Collections) but I can't extract these Attributes, I try with JSON(), get, _.each, _.map but no success !

No comments:

Post a Comment