Каков правильный жизненный цикл представления Marionette View?

В настоящее время я использую Marionette 2.4.1.

У меня есть представление родительского макета (A), которое содержит область, на которую будет отображаться дочерний вид макета (B). У меня есть метод onShow для представления (B), который правильно вызывается при отображении представления (B). Однако у меня есть onEmpty и onBeforeEmpty в представлении (B), чтобы ожидать, что они будут вызваны, когда представление (B) скрыто. Они вызываются из представления (A), где у меня есть функция, которая очистит область, которую заполняет представление (B), однако я передаю {preventDestroy: true} при пустом вызове.

Моя проблема в том, что я ожидал / ожидаю, что представление (B) подберет эти триггеры before:empty или empty, которые вызываются, когда #empty вызывается из представления (A), однако представление (B) не подбирает эти триггеры. Кажется, что даже вид (B) не улавливает эти триггеры.

Какова ожидаемая ситуация здесь? При просмотре исходного кода Marionette я вижу, что триггер onBeforeEmpty вызывается в соответствии с моим исходным кодом:

Marionette._triggerMethod = (function() {
    // split the event name on the ":"
    var splitter = /(^|:)(\w)/gi;

    // take the event section ("section1:section2:section3")
    // and turn it in to uppercase name
    function getEventName(match, prefix, eventName) {
      return eventName.toUpperCase();
    }

    return function(context, event, args) {
      var noEventArg = arguments.length < 3;
      if (noEventArg) {
        args = event;
        event = args[0];
      }

      // get the method name from the event name
      var methodName = 'on' + event.replace(splitter, getEventName);
      var method = context[methodName];
      var result;

      // call the onMethodName if it exists
      if (_.isFunction(method)) {
        // pass all args, except the event name
        result = method.apply(context, noEventArg ? _.rest(args) : args);
      }

      // trigger the event, if a trigger method exists
      if (_.isFunction(context.trigger)) {
        if (noEventArg + args.length > 1) {
          context.trigger.apply(context, noEventArg ? args : [event].concat(_.drop(args, 0)));
        } else {
          context.trigger(event);
        }
      }

      return result;
    };
  })();

Вот где я подозреваю, что он запускает метод onBeforeEmpty:

// get the method name from the event name
      var methodName = 'on' + event.replace(splitter, getEventName);
      var method = context[methodName];

Кажется, что контекст - вид (A).

Регион Марионты#Пустой:

// Destroy the current view, if there is one. If there is no
    // current view, it does nothing and returns immediately.
    empty: function(options) {
      var view = this.currentView;

      var preventDestroy = Marionette._getValue(options, 'preventDestroy', this);
      // If there is no view in the region
      // we should not remove anything
      if (!view) { return; }

      view.off('destroy', this.empty, this);
      this.triggerMethod('before:empty', view);
      if (!preventDestroy) {
        this._destroyView();
      }
      this.triggerMethod('empty', view);

      // Remove region pointer to the currentView
      delete this.currentView;

      if (preventDestroy) {
        this.$el.contents().detach();
      }

      return this;
    },

Итак, здесь this.triggerMethod('before:empty', view); похоже, что this относится к виду (A), а view относится к виду (B). Это предназначено? Я думал, что метод будет запускаться при просмотре (B)? Однако я также не вижу, чтобы метод запускался в представлении (A).


person reid    schedule 20.09.2016    source источник


Ответы (1)


Это this в this.triggerMethod('before:empty', view); относится к вашему региону вашего макета. Вы можете увидеть больше событий/методов жизненного цикла региона здесь: http://marionettejs.com/docs/v2.4.3/marionette.region.html#events-raised-on-the-region-during-show

Если вы ищете методы для использования в своем представлении, onDestroy и onBeforeDestroy, вероятно, то, что вам нужно. Представления «уничтожаются», а регионы «опустошаются». http://marionettejs.com/docs/v2.4.3/marionette.view.html#view-onbeforedestroy

person olan    schedule 20.09.2016