When developing Backbone applications, I often find myself instantiating models in views when dealing with nested data. Here's some example data:
{
name: Alfred,
age 27,
skills: [
{
name: 'Web development',
level: 'Mediocre'
},
{
name: 'Eating pizza',
level: 'Expert'
]
}
Say I have some view PersonView
that takes a person object PersonModel
as its model (where Alfred would be an instance). And let's say I want to render the person's skills as subviews. At this point I create a new view and a new model for dealing with the nested skills data. And this is where I suspect I'm doing something wrong, or at least something suboptimal.
var SkillModel = Backbone.Model.extend();
var SkillView = Backbone.View.extend({
tagName: 'li',
initialize: function() {
this.render();
},
render: function() {
this.$el.html(someTemplate(this.model));
}
});
var PersonView = Backbone.View.extend({
el: ...
initialize: ...
renderSkills: function() {
_.each(this.model.get('skills'), function(skill) {
var skillModel = new SkillModel(skill);
var skillView = new SkillView({ model: skillModel });
self.$el.append(skillView.el);
})
}
});
Should I really be doing this or is there some better pattern, that does not involve third-party libraries, that solves the problem? I feel like I'm not really decoupling the views and models in the best way. If you want a concrete question it's: Is this an anti-pattern?