Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

didInsertElement from controller?

I have an ember application with a controller header.js and a template header.hbs.

Now I have some javascript I need to execute at document $( document ).ready()

I saw on Ember Views there is didInsertElement but how do I do this from the controller?

// controllers/header.js
import Ember from 'ember';
export default Ember.Controller.extend({
});

// views/header.js
import Ember from 'ember';
export default Ember.Controller.extend({
});

// templates/header.js
test

I read several times it's not good practice to be using Ember Views?

like image 832
user391986 Avatar asked Oct 26 '14 16:10

user391986


People also ask

How do you destroy ember components?

js import Ember from 'ember'; export default Ember. Component. extend({ didInsertElement() { if(some_condition) { //if this condition is true then destory the component from DOM and remove all of its events. //destroy the component } } }); javascript.

What is an ember controller?

In Ember. js, controllers allow you to decorate your models with display logic. In general, your models will have properties that are saved to the server, while controllers will have properties that your app does not need to save to the server.

What is octane ember?

Ember Octane describes a set of new features that, when taken together, represent a foundational improvement to the way you use Ember. It has modern, streamlined components and state management that make it fun to build web applications.

What are Ember hooks?

As components are rendered, re-rendered and finally removed, Ember provides lifecycle hooks that allow you to run code at specific times in a component's life. To get the most use out of a component, it is important to understand these lifecycle methods.


2 Answers

the controller is not inserted (the view is) hence there is no didInsertElement.

If you need something to run once, you can write something like this:

import Ember from 'ember';
export default Ember.Controller.extend({
    someName: function () {  // <--- this is just some random name
        // do your stuff here
    }.on('init')  // <---- this is the important part
});
like image 152
amenthes Avatar answered Sep 28 '22 05:09

amenthes


A more actual answer (Ember 2.18+) while honouring the same principle as mentioned in user amenthes' answer: it's no longer advised to use Ember's function prototype extensions. Instead you can override the init() method of a controller directly. Do note that you'll have to call this._super(...arguments) to ensure all Ember-related code runs:

import Controller from '@ember/controller';

export default Controller.extend({
  init() {
    this._super(...arguments); // Don't forget this!

    // Write your code here.
  }
});
like image 45
Mirage Avatar answered Sep 28 '22 04:09

Mirage