1

我将组件的 0.4.0 分支用作 HTML 文件功能。我正在尝试执行以下操作:我有一个控制页面布局的组件。这个组件有一些子组件作为一个数组,并根据子组件中的一些数据将它们显示在页面的不同部分。类似于此的东西(由于布局限制,它们必须位于页面的不同部分):

<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>

该标志是从每个组件内的控件更新的。除了一个问题外,这很好用(每次我修改标志时都会刷新 DOM)。每次标志更改时都会重新创建子组件,而不是执行移动,例如,它被销毁并创建一个新的。这对我的用例来说是不幸的,原因有两个:

  1. 子组件具有相当高的创建成本(特别是在移动设备中),因为它执行一些图形工作。
  2. 子组件存储一些私有数据(对模型所做的更改的历史记录),这些数据要么 a)在移动到另一个部分时丢失,要么 b)必须存储在顶部组件中,从而污染其数据模型。

所以我想知道的是,有没有办法“移动”组件而不删除/重新创建它?

问候, V. Seguí

4

1 回答 1

3

是的 - 每个 Ractive 实例都有两种方法可以让你这样做:ractive.detach()ractive.insert(). 不幸的是,目前缺少文档,但这是您使用它的方式:

// 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 );

如果您要删除实例并立即重新插入它,则无需先将其分离 - 您只需ractive.insert(). 参数可以是 DOM 节点,但也可以是 CSS 选择器或元素的 ID。

这是一个 JSFiddle 演示:http: //jsfiddle.net/rich_harris/Uv8WJ/

您也可以使用内组件(即<subcomponent/>new Subcomponent().ractive.findComponent('subcomponent')

于 2014-02-28T13:43:24.317 回答