传递参数的骨干js

Backbone js passing arguments

本文关键字:js 参数      更新时间:2023-09-26

我刚开始阅读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传递。