Reputation: 11
I am using backgrid.js with backbone.js. I'm trying to populate JSON (user list) in backgrid. Below is my JSON,
[{"name": "kumnar", "emailId":"[email protected]", "locations":{"name":"ABC Inc.,", "province":"CA"} }]
I can access name & emailId as below,
var User = Backbone.Model.extend({}); var User = Backbone.Collection.extend({ model: User, url: 'https://localhost:8181/server/rest/user', }); var users = new User(); var columns = [{ name: "loginId", label: "Name", cell: "string" }, { name: "emailId", label: "E-mail Id", cell: "string" } ]; var grid = new Backgrid.Grid({ columns: columns, collection: users }); $("#grid-result").append(grid.render().$el); userEntities.fetch();
My question is, how do I add a column for showing locations.name?
I have specified locations.name in the name property of columns but it doesn't work. { name: "locations.name", label: "E-mail Id", cell: "string" }
Thanks
Upvotes: 1
Views: 2501
Reputation: 31
It's really easy to extend Cell (or any of the existing extensions like StringCell). Here's a start for you:
var DeepstringCell = Backgrid.DeepstringCell = StringCell.extend({
render: function () {
this.$el.empty();
var modelDepth = this.column.get("name").split(".");
var lastValue = this.model;
for (var i = 0;i<modelDepth.length;i++) {
lastValue = lastValue.get(modelDepth[i]);
}
this.$el.text(this.formatter.fromRaw(lastValue));
this.delegateEvents();
return this;
},
});
In this example you'd use "deepstring" instead of "string" for your "cell" attribute of your column. Extend it further to use a different formatter (like EmailFormatter) if you want to reuse the built-in formatters along with the deep model support. That's what I've done and it works great. Even better is to override the Cell definitions to look for a "." in the name value and treat it as a deep model.
Mind you, this only works because I use backbone-relational which returns Model instances from "get" calls.
Upvotes: 3
Reputation: 7244
Both backbone and backgrid currently don't offer any support for nested model attributes, although there are a number of tickets underway. To properly display the locations info, you can either turn the locations object into a string on the server and use a string cell in backgrid, or you can attempt to supply your own cell implementation for the locations column.
Also, you may try out backbone-deep-model as it seems to support the path syntax you are looking for. I haven't tried it before, but if it works, you can just create 2 string columns called location.name
and location.province
respectively.
Upvotes: 3