Is this an anti-pattern for instantiating models in Backbone.js views?

When developing Backbone applications, I often find that I instantiate models in looks when working with nested data. Here are some sample data:

{
  name: Alfred,
  age 27,
  skills: [
    {
      name: 'Web development',
      level: 'Mediocre'
    },
    {
      name: 'Eating pizza',
      level: 'Expert'
  ]
}

Let's say I have some kind PersonViewthat takes a person object PersonModelas its model (where Alfred will be an instance). And let me say that I want human skills to be sub-sectors. At this point, I create a new view and a new model for processing nested skills data. And here I suspect that 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);
    })
  }
});

- , , ? , . : -?

+4
1

, .

, :

var SkillModel = Backbone.Model.extend({
});
var SkillsCollection = Backbone.Collection.extend({
    model : SkillModel
});
var PersonModel = Backbone.Model.extend({

    /*
    ** Your current model stuff
    */

    //new functionality 

    skills : null,

    initialize : function(){
        //set a property into the model that stores a collection for the skills
        this.skills = new SkillsCollection;
        //listen to the model attribute skills to change
        this.on('change:skills', this.setSkills);
    },

    setSkills : function(){
        //set the skills of the model into skills collection
        this.skills.reset( this.get('skills') );
    }

});

, renderSkills :

var PersonView = Backbone.View.extend({
  renderSkills: function() {
     //this.model.skills <- collection of skills
    _.each(this.model.skills, function(skill) {
      var skillView = new SkillView({ model: skillModel });

      self.$el.append(skillView.el);
    })
  }
});

, . , , , /, . , . : https://github.com/afeld/backbone-nested

: :

var m = new PersonModel();
//nested collection is empty
console.log(m.skills.length);
m.set({skills : [{skill1:true}, {skill1:true}]});
//nested collection now contains two children
console.log(m.skills.length);

, "" , - , . , . .each , add, reset .. ( ).

: http://jsfiddle.net/9nF7R/24/

+1

Source: https://habr.com/ru/post/1525482/


All Articles