Backbone:LayoutView需要在CollectionView中监听ItemView

时间:2015-02-13 10:11:16

标签: javascript backbone.js triggers marionette

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

从谷歌搜索中,很多人提到在骨干网中使用库来嵌套对象,但我想弄清楚标准的做法是什么。

为了更清楚,我的问题是: 如何在我的childView(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));
          }

       });

1 个答案:

答案 0 :(得分:1)

使用CollectionView(http://marionettejs.com/docs/v2.3.2/marionette.collectionview.html#collectionviews-childevents)的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));
      }

   });