木偶布局:覆盖视图onclick

时间:2013-09-16 16:21:40

标签: backbone.js marionette

我有一个完美的布局视图。在四个子视图中的一个中,有一个用于创建“事件”的按钮。单击时,我希望子视图被单独的添加事件视图替换。

我不确定添加事件视图是在主布局逻辑中还是在子视图中触发。

index.js(布局父视图)

define([
  "marionette",
  'app/views/images/collection',
  'app/views/topPosts/collection',
  'app/views/clients/collection',
  'app/views/events/collection',
  "tpl!app/templates/index.html"
],
  function(Marionette, ImagesView, TopPostsView, ClientsView, EventsView, template) {
    "use strict";
    var AppLayout, layout;
    AppLayout = Backbone.Marionette.Layout.extend({
      template: template(),
      regions: {
        collection1: '#images',
        collection2: '#topPosts',
        collection3: '#clients',
        collection4: '#events'
      },
      onRender: function() {
        this.collection1.show(new ImagesView())
        this.collection2.show(new TopPostsView())
        this.collection3.show(new ClientsView())
        this.collection4.show(new EventsView())
      }
    })
    return new AppLayout()
  })

event / collection.js(我相信它会触发替换视图)

define(["marionette", "text!app/templates/events/collection.html", "app/collections/events", "app/views/events/item", 'app/views/events/create'], function (Marionette, Template, Collection, Row, CreateEventView) {
  "use strict"
  return Backbone.Marionette.CompositeView.extend({
    template: Template,
    itemView: Row,
    itemViewContainer: "ul",
    events: {
      'click #createEvent': 'onClickCreateEvent'
    },
    onClickCreateEvent: function () {
      //render create form over the events collection
    },
    initialize: function () {
      this.collection = new Collection()
      return this.collection.fetch()
    }
  })
})

event / item.js(上面集合的模型视图)

define(["marionette", "text!app/templates/events/item.html"], function(Marionette, Template) {
  "use strict";
  return Backbone.Marionette.ItemView.extend({
    template: Template,
    tagName: "li"
  })
})

我尝试将其放在event / collection.js中,但它只是删除了项目视图

onClickCreateEvent: function () {
      this.$el = new CreateEventView().$el
      this.$el.render(); return this;
    },

1 个答案:

答案 0 :(得分:2)

将在包含单击元素的视图中触发事件。但是,只要您未在事件上调用stopPropagation(),事件就会传播到父视图。但是,CompositeView不应该负责替换自己;应该对父视图负责(我相信AppLayout)。处理视图交换的一种方法是:

// index.js
AppLayout = Backbone.Marionette.Layout.extend({
  ...
  events: {
    'click #createEvent': 'onClickCreateEvent'
  },
  ...
  onClickCreateEvent: function(e) {
    this.collection4.show(new CreateEventsView());
  },
  ...

这种方法的一个缺点是,您绑定事件的DOM元素与该Layout的模板没有直接关系。