主干:LayoutView需要在CollectionView内的ItemView中列出

Backbone: LayoutView needs to listenTo a ItemView inside a CollectionView

本文关键字:ItemView 内的 CollectionView LayoutView 主干      更新时间:2023-10-10

我正在尝试使用Backbone中的listenTo方法来侦听子视图、集合视图以及集合视图父LayoutView中的触发器。

从谷歌搜索中,很多人提到在主干网中使用嵌套对象库,但我正在努力找出标准的方法

更清楚地说,我的问题是:如何使子视图(ItemDetailsView)中的触发器冒泡到父LayoutView(MyItemsList.Layout)

      var ItemDetailsView = Backbone.Marionette.LayoutView.extend({
          template: JST["items/item"],
          tagName: "li",
          className: "item",
          events: {
              "click @ui.btn": "callTrigger"
          },
          callTrigger: function() {
               this.trigger("hello:world");
           }
      )}; 
      var ItemListView = Backbone.Marionette.CollectionView.extend({
           tagName: "ul",
           childView: itemDetailsView
       });
      MyItemsList.Layout = Marionette.LayoutView.extend({
          template: JST["items/current-items"],
          tagName: "section",
          className: "current-items",
          onShow: function() {
               var listCollection = this.model.currentListCollection;
               var listView = new MyListView({
                    collection: listCollection
               });
               this.listenTo(listView.collection, "hello:world", _.bind(function() {
                    console.log("I heard that!")
               }, this));
          }
       });

使用CollectionView的childEvents属性(http://marionettejs.com/docs/v2.3.2/marionette.collectionview.html#collectionviews-childevents)。

然后,您的代码可以编写如下。

  var ItemDetailsView = Backbone.Marionette.LayoutView.extend({
      template: JST["items/item"],
      tagName: "li",
      className: "item",
      events: {
          "click @ui.btn": "callTrigger"
      },
      callTrigger: function() {
           this.trigger("hello:world");
       }
  )}; 
  var ItemListView = Backbone.Marionette.CollectionView.extend({
       tagName: "ul",
       childView: itemDetailsView,
       // This callback will be called whenever a child is rendered or emits a `render` event
       childEvents: {
          "hello:world": function() {
            console.log("a childView said hello world!");
            this.triggerMethod('child:hello:world');
          }
        }
   });
  MyItemsList.Layout = Marionette.LayoutView.extend({
      template: JST["items/current-items"],
      tagName: "section",
      className: "current-items",
      onShow: function() {
           var listCollection = this.model.currentListCollection;
           var listView = new MyListView({
                collection: listCollection
           });
           this.listenTo(listView, "child:hello:world", _.bind(function() {
                console.log("I heard that!")
           }, this));
      }
   });