How to run jquery code when changing templates in ember.js?

Member

by ryleigh , in category: Javascript , 4 months ago

How to run jquery code when changing templates in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by aubrey , 4 months ago

@ryleigh 

You can run jQuery code when changing templates in Ember.js by using the didInsertElement hook in your Ember component.


Here’s an example of how you can run jQuery code when changing templates in Ember.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import Ember from 'ember';

export default Ember.Component.extend({

  didInsertElement() {
    this._super(...arguments);

    Ember.run.scheduleOnce('afterRender', this, function() {
      // Your jQuery code here
      this.$('.my-element').css('background-color', 'red');
    });
  }

});


In this example, we are using the didInsertElement hook in an Ember component to run some jQuery code after the element has been inserted into the DOM. The Ember.run.scheduleOnce('afterRender', this, function() {}) function ensures that the jQuery code is run after the element has been rendered on the page.


You can place your jQuery code inside the function() {} block, and target the element(s) you want to manipulate using this.$(). In this example, we are selecting an element with the class ‘my-element’ and changing its background color to red.


By using the didInsertElement hook in your Ember component, you can ensure that your jQuery code is run every time the template is changed or refreshed.