2

I need to know if the el in a View has been attached to the DOM because I'm trying to apply a jQuery plugin, but the plugin requires the el to be in the DOM first.

Inspired by How do I check whether a jQuery element is in the DOM? I get this to work:

render : function() {
    ...
    if (this.$el.closest('html').length)    // test if in DOM
        this.$el.someJqueryPlugin();
    return this;
}

I also need the owner of this view to trigger an 'onshow' right after the el is inserted to the DOM, which is doable, but kind of clumsy.

Another solution I can think of is to do this:

var el = $('<div>').appendTo(somewhereInsideDOM);
var view = new view(el:el);

In this case, the el will always be attached to the DOM and much less clumsy this way, but the downside would be manipulation of el means manipulating the DOM. Lastly, with this method, the this.className is not respected. An additonal .addClass(this.className) is needed.

Any other solution?

Community
  • 1
  • 1
Henry
  • 32,689
  • 19
  • 120
  • 221
  • You want to be notified when the `el` is attached to the DOM? – mu is too short Oct 18 '12 at 23:29
  • sure, if such thing exists. `this.$el.closest('html').length` works but seems a little hackish. If there's something better, pls let us know. My colleague used `.livequery()` but I don't feel right using that. I'm now using my 2nd solution, where `el` is always in DOM – Henry Oct 18 '12 at 23:33
  • `closest('html')` works if you want to know if it is in there right now but it won't tell you if someone adds `el` to the DOM later. `livequery` is pretty kludgy as well. You might be able to specify that people **must** add the `el` to the DOM as part of calling `render` and then use the `setTimeout(..., 0)` hack. What exactly does `onshow` need to do? – mu is too short Oct 18 '12 at 23:42
  • There was a question recently asked about something similar: http://stackoverflow.com/questions/12785861/how-to-check-an-element-retrieved-from-dom-is-still-present-in-dom – JayC Oct 19 '12 at 03:40

1 Answers1

1

If element NEEDS to be in the DOM, you are better off appending it to body, e.g.

var el = $('<div />').css({ display: 'none' }),
    view;

$(body).append(el);
view = new View({ el: el });
el.somejQueryPlugin().show();

Hope this helps.

mvbl fst
  • 5,213
  • 8
  • 42
  • 59