Zichen Ma
Zichen Ma

Reputation: 987

how to trigger a function automatically in ember.js action helper?

I am new to ember.js and working on an application to highlight text like below:

<div>
  <h3 class = "title" {{action "highlight" "title"}}>{{document.title}}</h3>
  <div class = "date" {{action "highlight" "date"}}>{{document.date}}</div>
  <p class = "content" {{action "highlight" "content"}}>{{document.contents}}
  </p>
</div>

I created a function highlight which will get the class name and highlight the search text the user input. This function works fine, but I have to click to trigger this highlight function. Is there any way in ember action helper can trigger this function whenever the div node rendered or automatically triggered?

Upvotes: 0

Views: 505

Answers (2)

wuarmin
wuarmin

Reputation: 4005

I don't understand your use-case entirely, but I think actions are not a good choice for your problem. I would recommend reading the ember guides about computed properties. These properties are recomputed everytime an underlying property changes.


  highlightedContent: computed('userInput', 'content', function() {
    ....
    //return computedContent;
  })

I would also recommend reading the guides about handlebar-helpers. You could write a highlight-helper.

Upvotes: 1

Johan de Bruin
Johan de Bruin

Reputation: 73

What you probably need is to implement the hook didInsertElement, this will trigger as soon your component got rendered in the screen.

Example:

import Component from '@ember/component';
export default Component.extend({
    didInsertElement() {
        this._super(...arguments);
        const title = this.element.querySelector('.title');
        // do something with the title
    },
});

More information about didInsertElement can be found in this guide: https://guides.emberjs.com/v2.18.0/components/the-component-lifecycle/

Upvotes: 2

Related Questions