Jo Liss
Jo Liss

Reputation: 32945

Ember.js: Check if view element is inserted into DOM

In a method on an Ember.View subclass, I would like to make changes to the DOM only if the view element has already been inserted into the DOM. How can I check that?

I know I could create an auxiliary property like so:

didInsertElement: function() {
  this.set('elementIsInserted', true);
}
willDestroyElement: function() {
  this.set('elementIsInserted', false);
}

But is there some canonical, built-in way?

I didn't find anything skimming view.js, but perhaps I'm missing something.

Upvotes: 6

Views: 4197

Answers (2)

weltraumpirat
weltraumpirat

Reputation: 22604

Every view has a _state property, which is set to "inDOM" when the element is inserted.

if (this._state=="inDOM") doStuff();

should work. Make sure you have the correct this!

Upvotes: 13

Panagiotis Panagi
Panagiotis Panagi

Reputation: 10077

If you want to avoid having to set an auxiliary flag, you can extend Ember.View:

Ember.View.reopen({
    didInsertElement: function() {
       this.set('elementIsInserted', true);
       this._super();
    },

    willDestroyElement: function() {
       this.set('elementIsInserted', false);
       this._super();
    }
});

Now every View that extends Ember.View will get the above.

Also a member of the core team suggested that you avoid referring to inDOM as it is an internal variable and not intended to be used in code.

Upvotes: 9

Related Questions