Grapesjs provide two lifecycle methods: init()
and onRender()
, I am actually quite confused with those two hooks:
As the doc said:
- Local hook:
view.init(
) method, executed once the view of the component is initiliazed- Local hook:
view.onRender()
method, executed once the component is rendered on the canvas
init({ model }) {
// Do something in view on model property change
this.listenTo(model, 'change:prop', this.handlePropChange);
// If you attach listeners on outside objects remember to unbind
// them in `removed` function in order to avoid memory leaks
this.onDocClick = this.onDocClick.bind(this);
document.addEventListener('click', this.onDocClick)
},
// Do something with the content once the element is rendered.
// The DOM element is passed as `el` in the argument object,
// but you can access it from any function via `this.el`
onRender({ el }) {
const btn = document.createElement('button');
btn.value = '+';
// This is just an example, AVOID adding events on inner elements,
// use `events` for these cases
btn.addEventListener('click', () => {});
el.appendChild(btn);
},
For example, i can access this.el
in both methods to get dom element. if I want to attach a event listener on this.el
, which one is more appropriate to do such operation?
In general, what's difference between those two methods, and in what scenario should i use them?