Backbone js传递参数

Backbone js passing arguments

我是阅读 Backbone js 的新手,我在 传递 参数 方面遇到了一些严重的问题 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();

如你所见,我有这个功能:onSongAdded 我们有一些内置事件,例如 add 可以得到 3 个参数,如下所示: 添加(集合、模型、选项) 我如何在我的代码中使用这些参数? 你能帮帮我吗?

el 选项用于将视图指向 DOM 中已存在的元素。您的项目视图应该创建新的 <li> 元素,因此您应该改用 tagName 选项。

在您的集合视图构造函数中,您已经定义了 el 选项,并且在实例化它时传递了一个不同的 el 选项。如果 #songs 是 DOM 中的 <uL>,则在构造函数中定义 el: "ul", 没有用。

此外,无需手动实例化模型,您只需将对象传递到集合中,集合将在内部完成。并且不要将集合作为 model 传递,将其作为 collection.

传递