I'm using the 0.4.0 branch for the components as HTML files functionality. I'm trying to do the following: I have a component that controls the layout of a page. This component has some subcomponents as an array and displays them on different parts of the page based on some data in the subcomponent. Something akin to this (due to layout restrictions they have to be in different parts of the page):

<div id="section1"> 
     <h1> Section 1 </h1>
    {{# subcomponents}}
       {{#isflagsection1(flag)}}
         <subcomponent flag={{flag}}/>
       {{/isflag}}
     {{/subcomponents}}
</div>

<div id="section2"> 
     <h1> Section 2 </h1>
    {{# subcomponents}}
        {{#isflagsection2(flag)}}
            <subcomponent flag={{flag}}/>
        {{/isflag}}
    {{/subcomponents}}
</div>
<div id="section3"> 
    <h1> Section 3 </h1>
    {{# subcomponents}}
        {{#isflagsection3(flag)}}
          <subcomponent flag={{flag}}/>
        {{/isflag}}
     {{/subcomponents}}
</div>

The flag is updated from controls within each component. this works great (the DOM is refreshed each time I modify the flag) except for one issue. Instead of performing a move, the subcomponent is recreated every time the flag changes, e.g. it's destroyed and created a new. This is unfortunate for my use case because of two reasons:

  1. The subcomponent has a rather heavy creation cost (specially in mobile) since it performs some graphics work.
  2. The subcomponent stores some private data (a history of changes made to the model) that either a) gets lost when it's moved along to another section or b) has to be stored in the top component polluting it's data model.

So what I would like to know is, is there a way to "move" the component without deleting/recreating it?

Regards, V. Seguí

有帮助吗?

解决方案

Yes - every Ractive instance has two methods that allow you to do this: ractive.detach() and ractive.insert(). Unfortunately the documentation is currently lacking, but here's how you use it:

// remove the instance from the DOM, and store a document
// fragment with the contents
docFrag = ractive.detach();

// insert the instance into the container element, immediately
// before nodeToInsertBefore (the second argument is optional -
// if absent or `null` it means 'insert at end of container'
ractive.insert( container, nodeToInsertBefore );

If you're removing the instance and immediately reinserting it, there's no need to detach it first - you can just do ractive.insert(). The arguments can be DOM nodes, but they can also be CSS selectors or the IDs of elements.

Here'a a JSFiddle demonstrating: http://jsfiddle.net/rich_harris/Uv8WJ/

You can also do this with inline components (i.e. <subcomponent/> as opposed to new Subcomponent(). In this JSFiddle, we're using ractive.findComponent('subcomponent') method to get a reference to the instance: http://jsfiddle.net/rich_harris/f28t5/.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top