【问题标题】:Don't destroy DOM elements with #each in Ember/Handlebars不要在 Ember/Handlebars 中使用 #each 破坏 DOM 元素
【发布时间】:2014-09-24 14:55:40
【问题描述】:

我正在尝试为 ember 中的绑定数组制作 CSS 动画。我想在每次值变化时做一个动画,但它不会动画,因为每当它迭代的数组发生变化时,Handlebars 都会完全替换 #each 助手中的所有内容。

这是我正在做的简化版本:

{{#each array}}
    {{custom-component value=this}}
{{/each}}

以及自定义组件的模板:

<script type="text/x-handlebars" data-template-name="components/custom-component">
    <li {{bind-attr style=customAnimatedStyleThatChangesWithValue}}>{{value}}</li>
</script>

可以使用占位符数组预渲染它,例如:

{{#each placeholderArray}}
    {{custom-component value=[don't know what to put here]}}
{{/each}}

但是,正如代码块中所述,我不能在自定义组件调用中执行value=array[this]。我不认为自定义组件会在值更改时重新渲染,但我不知道在使用#each 迭代时如何传入不同数组的值。

TLDR:如何在数组更改时迭代组件数组而不破坏和重新创建它们?

【问题讨论】:

    标签: ember.js handlebars.js


    【解决方案1】:

    所以看起来我在使用占位符数组之前走在正确的轨道上。以下是我最终解决此问题的方法:

    {{#each arrayPosition in placeholderArray}}
        {{custom-component value=array arrayPosition=arrayPosition}}
    {{/each}}
    

    我传递了我想要的原始数组作为组件中的值,还传递了我所在的占位符数组的位置。这让我可以在控制器中执行以下操作:

    App.CustomComponentController = Ember.Component.extend({
        ...
        customAnimatedStyleThatChangesWithValue: function() {
            //Grab the original array
            var valueArray = this.get('value');
            //Use arrayPosition to get the value you initially wanted to pass through
            var value = valueArray[+this.get('arrayPosition')];
            return "width: "+value+"px"; //Or whatever you're animating
        }.property('value')
    });
    

    这样做使得只要 placeholderArray 不变,自定义组件就不会被销毁然后重新创建。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 2015-02-14
      相关资源
      最近更新 更多