正在读取Ractive.js中的计算属性

Reading computed properties in Ractive.js

本文关键字:计算 属性 js 读取 Ractive      更新时间:2023-09-26

我正在努力找出实现这一目标的最佳方式。我可能会用错误的方式思考,但这正是我"想要"实现的:

<div>
    {{#if selection}}
        <div>There is a selection in Component!</div>
    {{/if}}
    <Component />
</div>

其中selectionComponent中的计算属性,我希望在外部范围中使用它。有没有任何方法可以引用组件实例的属性?

例如:

<div>
    {{#if foo.selection}}
        <div>There is a selection in Component!</div>
    {{/if}}
    <Component id="foo" />
</div>

或者这是错误的思考方式。我唯一能想到的其他方式就是使用事件。

<div>
    {{#if selection}}
        <div>There is a selection in Component!</div>
    {{/if}}
    <Component on-selection="select" />
</div>

但这并不优雅,因为它需要额外的代码:

ractive.on("selection", function(e) { this.set("selection", ...); });

从版本0.8开始,可以直接将事件映射到数据值(请参阅http://jsfiddle.net/0zubyyov/)它很好地将组件内部与父级解耦:

模板:

<script id='template' type='text/ractive'>
    {{#if selected}}selected!{{/if}}
    <component on-select='set("selected", $1)'/>
</script>
<script id='component' type='text/ractive'>
    <input type='checkbox' on-change='fire("select", event.node.checked)'>
</script>

javascript:

Ractive.components.component = Ractive.extend({
    template: '#component',
    data: { selected: false }
});
var r = new Ractive({
    el: document.body,
    template: '#template'
});

使用0.7,您可能会考虑将一个值传递给保持最新的组件(请参阅http://jsfiddle.net/gr6d7vs8/)。我在这篇文章中更明确地谈到了处理计算的属性:

<script id='template' type='text/ractive'>
    {{#if selected}} selected! {{/if}}
    <component selected='{{selected}}'/>
</script>
<script id='component' type='text/ractive'>
    <input type='checkbox' checked='{{checked}}'>
</script>

javascript:

Ractive.components.component = Ractive.extend({
    template: '#component',
    data: { checked: false, allowed: true },
    computed: {
        isChecked () {
            return this.get('checked') && this.get('allowed')
        }
    },
    oninit(){
        this.observe('isChecked', isChecked => {
            this.set('selected', isChecked);
        });
    }
});