Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ember.js

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.

like image 342
Jo Liss Avatar asked May 13 '12 01:05

Jo Liss


2 Answers

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!

like image 78
weltraumpirat Avatar answered Sep 25 '22 23:09

weltraumpirat


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.

like image 24
Panagiotis Panagi Avatar answered Sep 23 '22 23:09

Panagiotis Panagi