繁体   English   中英

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个这样的参数:add(collection,model,options)如何在我的代码中使用这些参数? 你能帮助我吗?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM