Search code examples
javascriptmarionette

Marionette onAttach event


Marionette version 3.2.0

onAttach lifecycle event not fire

according to doc

The events marked with "*" only fire if/when the region's el is attached to the DOM.

cat guru explain why ?

Mn.View.extend({
    tagName: 'table',
    className: 'table',
    template: _.template(template),
    regions: {
        body: {
            el: 'tbody',
            replaceElement: true
        }
    },
    initialize(options) {
      console.log(Mn.isNodeAttached(this.el)); // false
      setTimeout(() => console.log(Mn.isNodeAttached(this.el)), 0); // true
    },
    serializeData() {
      return {
        foo: 'bar'
      }
    },
    onRender() {
      this.showChildView('body', new TableBodyView());
    },

    onAttach() {
      // why onAttach not work ?
      console.log('attached');
    }

  });

Solution

  • It's not clear how you are instantiating your view and attaching it to the page, but the onAttach method only fires when 'showing' a view into a region. So, if you are manually rendering and attaching a view to the DOM for example, it won't fire.

    The snippet below shows an example where View's onAttach method will fire:

    const App = Mn.Application.extend({
        region: '.content',
        onStart: function() {
            this.showView(new View());
        }
    });
    
    new App().start();
    

    Fiddle: https://jsfiddle.net/wa69p3kj/

    Note that this does not need to be shown in an Application's region necessarily -- the onAttach method will fire when showing a view with showChildView as well.