Search code examples
javascripteventsbackbone.jsparameter-passingbuilt-in

Backbone js passing arguments


I'm new at reading Backbone js and I have some serious problems with passing arguments in Backbone js.

var Song = Backbone.Model.extend();
var Songs = Backbone.Collection.extend({
  model: Song
});
var SongView = Backbone.View.extend({
  el: "li",
  render: function() {
    this.$el.html(this.model.get("title"));
    return this;
  }
});
var SongsView = Backbone.View.extend({
  el: "ul",
  initialize: function() {
    this.model.on("add", this.onSongAdded, this);
  },
  onSongAdded: function(song) { // when object is added to  a collection add event is triggerd 
    // the handler for this event get an argument which is the object that was just added
    //in this case it refers to a song model so we simply pass it to our songView which is responsible for rendering a song an then we use jquery append method 
    // to append it to our list
    var songView = new SongView({
      model: Song
    });
    this.$el.append(songView.render().$el);

  },
  render: function() {
    var self = this;
    this.model.each(function(song) { //
      var songView = new SongView({
        model: Song
      });
      self.$el.append(songView.render().$el);
    });
  }
});
var songs = new Songs([
  new Song({
    title: "1"
  }),
  new Song({
    title: "2"
  }),
  new Song({
    title: "3"
  })
]);
var song_1 = new Song({
  title: "hello"
});
var songsView = new SongsView({
  el: "#songs",
  model: Songs
});
songsView.render();

as you can see I have this function: onSongAdded we have some built-in events such as add that get 3 arguments like this: add(collection, model , options) how can I use these arguments in my code? can you help me?


Solution

  • el option is for pointing the view to an element already existing in DOM. Your item views should be creating new <li> elements so you should be using tagName option instead.

    In your collection view constructor you've defined el option and you're passing a different el option while instantiating it. If #songs is a <uL> in DOM, then no use in defining el: "ul", in constructor.

    Also, there is no need to manually instantiate models, you can just pass objects into collections and collection will do it internally. And don't pass collection as model, pass it as collection.