如何动态创建 Ractive 的子组件并以编程方式更改它们 [英] How to create Ractive's subcomponents dynamically and change them programmatically

查看:12
本文介绍了如何动态创建 Ractive 的子组件并以编程方式更改它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I can instantiate (sub)components manually using tags, but I don't know how to do it dynamically, or, how to insert and remove different components in the same area using tags.

Today I instantiate each (sub)component this way:

Ractive.load( '/templates/global/example.html' ).then( function ( Example )
{
       ractive.components.example = new Example( { el : 'aside' } );
});

But the new (sub)component can't see the data of it's parent instance in mustache, only his own data.

解决方案

Here's a dynamic component:

Ractive.components.dynamic = Ractive.extend({
    template: '<component/>',
    components: {
        component: function() {
            return this.get('name');
        }
    },
    oninit: function(){
        this.observe('name', function(){
            this.reset();
        }, { init: false});
    }
});

Just pass in the name of the component it should implement:

<dynamic name='{{name}}'/>

See it in action below

Ractive.components.a = Ractive.extend({ template: 'I am A {{foo}}' });
Ractive.components.b = Ractive.extend({ template: 'I am B {{foo}}' });
Ractive.components.c = Ractive.extend({ template: 'I am C {{foo}}' });

Ractive.components.dynamic = Ractive.extend({
    template: '<component/>',
    components: {
        component: function() {
            return this.get('name');
        }
    },
    oninit: function(){
        this.observe('name', function(){
            this.reset();
        }, { init: false});
    }
});


var r = new Ractive({
    el: document.body,
    template: '#template',
    data: {
        foo: 'foo',
        list: ['a', 'b', 'c'],
        name: 'a'
    }
});

<script src="http://cdn.ractivejs.org/latest/ractive.js"></script>
<script id='template' type='text/ractive'>
   
    {{#each list}}
    <input type='radio' name='{{name}}' value='{{.}}'>{{.}}
    {{/each}}
    <br>
    <dynamic name='{{name}}'/>
       
</script>

这篇关于如何动态创建 Ractive 的子组件并以编程方式更改它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆