0

In our project we are using Ractive together with Backbone. Backbone.View has a "setElement" method, that basically sets the el property of a Backbone.View, thus allowing to attach the View to a different element of the DOM. I was wondering if there is a similar functionality for a Ractive object. Simply changing the el property of a Ractive object doesn't do the trick.

var oRactive = new Ractive(
{
    "data": someData,
    "el": someDomElement,
    "template": someTemplate
});

// ... after doing some other stuff we'd like to set oRactive do a different el

// this.doesn't do the trick
oRactive.el = someOtherDomElement;

// this puts the renderedHTML in our DOM element but binding doesn't work
$(someOtherDomElement).html(oRactive.renderedHTML());

I'm not really surprised that the above doesn't work. Question is: Is there a way to make it work or is it generally impossible?

I am aware that I could just append oRactive.el to "someOtherDomElement" but that's not quite what I want.

skeptic35
  • 61
  • 5

1 Answers1

0

This isn't something that Ractive currently supports, though it might in future. You could try doing the following:

frag = document.createDocumentFragment();

// move contents into the document fragment...
while ( oRactive.el.firstChild ) {
  frag.appendChild( oRactive.el.firstChild );
}

// ...then into the DOM
someOtherDomElement.appendChild( frag );

// update oRactive.el so oRactive.find() still works
oRactive.el = someOtherDomElement;

Ractive stores references to individual nodes - in most cases it doesn't care about the actual shape of the DOM, and your situation shouldn't pose any obstacles (though I'd be interested to know if you run into any bugs doing this).

Rich Harris
  • 28,091
  • 3
  • 84
  • 99
  • Yup, that actually works. Thanks! No problems encountered so far. If I do run into any bugs with that, you'll be the first to know ;) And I'd really like to see this feature in a future version of Ractive. – skeptic35 Nov 08 '13 at 12:29
  • 1
    FYI this is now supported - you can do `ractive.insert(node,anchor)` to detach the instance from its current location and re-insert it inside `node`, before `anchor` (which is optional). You can also do `ractive.detach()` to remove an instance from the DOM without destroying it (i.e. to reinsert later). This method returns a document fragment containing all the instance's nodes. – Rich Harris Dec 25 '13 at 01:30