【问题标题】:Ractive.js, access to parent property by named propertiesRactive.js,通过命名属性访问父属性
【发布时间】:2016-02-20 13:01:45
【问题描述】:

我有一个数据对象:

var data = {
    examples: [
    {
        type: 'a',
        message: 'a'
    },
    {
        type: 'b',
        message: 'b'
    },
    {
        type: 'c',
        message: 'c'
    }
    ],
    filter: {
        a: true,
        b: false,
        c: true
    }
};

我只想显示 examples 中的那些项目,其中 examples.typefiltertrue /em> 对象。

为了说明问题,让我为模板编写伪代码:

<ol>
    {{#each examples}}
        {{#if ../filter[type]}}
            <li>{{message}}</li>
        {{/if}}
    {{/each}}
</ol>

我需要访问父对象属性,我可以通过 ../ 来完成,并使用命名属性从 filter 对象中获取数据。

我该怎么做?我使用 RactiveJS。

【问题讨论】:

    标签: javascript templates mustache ractivejs


    【解决方案1】:

    您的伪代码 99% 正确。唯一的问题是,在{{#each ... }} 块内,您需要提升两个 级别的../../filter

    从单个数组项到数组的一个去:

    root/examples/0 --> root/examples
    

    还有一个从数组到数据根:

    root/examples --> root
    

    现在找到过滤器的上下文是正确的:

    root/filter
    

    但是,由于filter已经在ractive实例数据根目录,你可以直接使用~/filter语法直接访问:

    <ol>
        {{#each examples}}
            {{#if ~/filter[type]}}
                <li>{{message}}</li>
            {{/if}}
        {{/each}}
    </ol>
    

    new Ractive({
      el: document.body,
      template: '#template',
      data: {
        examples: [
        {
            type: 'a',
            message: 'a'
        },
        {
            type: 'b',
            message: 'b'
        },
        {
            type: 'c',
            message: 'c'
        }
        ],
        filter: {
            a: true,
            b: false,
            c: true
        }
      }
    });
    <script src='http://cdn.ractivejs.org/edge/ractive.min.js'></script>
    <script id='template' type='text/html'>
    <ol>
        {{#each examples}}
            {{#if ~/filter[type]}}
                <li>{{message}}</li>
            {{/if}}
        {{/each}}
    </ol>
    </script>

    【讨论】:

    • 我刚刚以类似的方式解决了这个问题,并想分享解决方案。刷新了这个页面,看到了你的精彩解释。在我的情况下,我只使用了 {{#if filter[type]}} 并且似乎它有效。不过,../../filter 的可读性更好,至少对我来说是这样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多