木偶视图事件触发器未被侦听器捕获

时间:2013-11-12 11:47:00

标签: javascript backbone.js marionette

有人能弄明白我的事件没有被收听的原因吗?

如果我将事件和函数放在ItemView中,触发器永远不会在视图控制器中被注意到

如果我将事件监听器和相应的函数放在CollectionView中,触发器会在视图控制器中被注意到并且它很开心,除了我无法访问单个模型。

ListingView.ListingItem = Marionette.ItemView.extend({
  tagName: "div",
  className: "grid-flex  mix-10-70-15 row-wrap itemDetail",
  template: "#listing-item",
  /*
    Using the code below in the ItemView gives me access to
    the current model, but the trigger isn't picked up in the controller
  */
  events: {
    "click":"editItemDetail"
  },
  editItemDetail: function() {
    console.log('You clicked');
    this.trigger("itemsListing:editCurrentItem", this.model);
  }
});

ListingView.ListingItems = Marionette.CollectionView.extend({
  tagName: "div",
  className: "listItemsWrapper",
  template: "#listing-items",
  itemView: ListingView.ListingItem,
  /*
    Putting the code below in the CollectionView
    gets acted on by the controller. I get the alert
    but I can't get access to the selected model
  */
  events: {
    "click":"editItemDetail"
  },
  editItemDetail: function() {
    console.log('You clicked');
    this.trigger("itemsListing:editCurrentItem", this.model);
  }
});

和控制器代码:

var listingView = new ListingView.ListingItems({
collection: listCollection
});

tillRollView.on("itemsListing:editCurrentItem", function(model) {
    alert('Gotcha baby!');
    console.log(model);
});

我想知道为什么控制器不喜欢我在ItemView中的触发器(我在我的应用程序的其他地方成功地这样做了)。我也想知道我是否可以从我的CollectionView中获取模型。无论哪种方式都可以让我的应用程序正常工作,提前谢谢。

1 个答案:

答案 0 :(得分:4)

我认为当事件从ItemView中的CollectionView触发时,会以itemview:为前缀。

在你的情况下会给出:

tillRollView.on("itemview:itemsListing:editCurrentItem", function(model) {
    alert('Gotcha baby!');
    console.log(model);
});

来自木偶official documentation

  

当集合视图中的项视图触发事件时,即   事件将通过父集合视图冒泡   “itemview:”前置于事件名称。