Backbone js传递参数

时间:2016-07-20 10:40:05

标签: javascript events backbone.js parameter-passing built-in

我是第一个阅读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个这样的参数: 添加(集合,模型,选项) 如何在我的代码中使用这些参数? 你能救我吗?

1 个答案:

答案 0 :(得分:0)

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

在您的集合视图构造函数中,您已定义el选项,并且在实例化时会传递不同的el选项。如果#songs是DOM中的<uL>,则无法在构造函数中定义el: "ul",

此外,无需手动实例化模型,只需将对象传递到集合中,集合就可以在内部进行。并且不要将收集作为model传递,将其作为collection传递。