Ember.js:检查是否将视图元素插入DOM

Jo *_*iss 6 ember.js

在Ember.View子类的方法中,我想仅在视图元素已插入 DOM 时才对DOM进行更改.我该怎么检查?

我知道我可以像这样创建一个辅助属性:

didInsertElement: function() {
  this.set('elementIsInserted', true);
}
willDestroyElement: function() {
  this.set('elementIsInserted', false);
}
Run Code Online (Sandbox Code Playgroud)

但是有一些规范的,内置的方式吗?

我没有找到任何略读view.js,但也许我错过了一些东西.

wel*_*rat 13

每个视图都有一个_state属性,在插入元素时将其设置为"inDOM".

if (this._state=="inDOM") doStuff();
Run Code Online (Sandbox Code Playgroud)

应该管用.确保你有正确的this!


Pan*_*agi 9

如果您想避免设置辅助标志,可以扩展Ember.View:

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

    willDestroyElement: function() {
       this.set('elementIsInserted', false);
       this._super();
    }
});
Run Code Online (Sandbox Code Playgroud)

现在,每个扩展Ember.View的View都将获得上述内容.

此外,核心团队的成员建议您避免引用inDOM它,因为它是一个内部变量,并不打算在代码中使用.