Populate Backbone Marionette Views with data from

2019-07-04 02:20发布

Im trying to fetch the data/api using a node/express route with data stored in mongo/mongoose and show it inside Backbone Marionette...

The route im using is this:

enter code here`app.get('/cats', function(req, res){
Cat.find({}, function (err, docs) {
res.send(docs);
  });
});

2) When I go to localhost:3000/cats, I get the json working as:

[
{
"__v": 0,
"_id": "51318ce9a7ff43f808000003",
"catname": "Jonas"
},
{
"catname": "Justin",
"_id": "51416268a8225e7413000001",
"__v": 0
},
{
"catname": "Bobby",
"_id": "51416268a8225e7413000001",
"__v": 0
}
]

3) Now how can I have the collection/model/itemview/etc use this json data from my db?

I usually get this far:

MyCat = Backbone.Model.extend({});

MyCats = Backbone.Collection.extend({
model: MyCat,
url: '/cats'
});

CatView = Backbone.Marionette.ItemView.extend({
template: "#cats-template",
tagName: 'li',
className: 'cat'
});

AngryCatsView = Backbone.Marionette.CompositeView.extend({
tagName: "ul",
id: "cats",
template: "#cats-template",
itemView: CatView,

appendHtml: function(collectionView, itemView){
collectionView.$("ul").append(itemView.el);
}
});

But then im not sure which type of initializer to use. I've seen examples with hardcoded json, but none from a db.

3条回答
姐就是有狂的资本
2楼-- · 2019-07-04 02:44

Problem was this... var thecats= myCats(); thecats.fetch(); Hope it helps someone

查看更多
forever°为你锁心
3楼-- · 2019-07-04 02:53

Not sure if this will work for your situation but on your collection, add a parse method that accepts your data. You may have a nested array that Backbone isn't able to retrieve the internal data from.

parse: function(data) {
  return data[0];
}

I would add a debug point inside this parse method to see if the data being passed in is nesting the data.

查看更多
We Are One
4楼-- · 2019-07-04 03:06

Nowhere in the code you've posted have you actually fetched your collection from the server.

Attempt this:

var catCollection = new MyCats();
catCollection.fetch();

var angryCatsView = new AngryCatsView({collection: catCollection});
angryCatsView.render();
查看更多
登录 后发表回答