使用ajax更改组件。 (Ractivejs)

时间:2014-12-22 08:02:29

标签: ractivejs

views.list = Ractive.extend({/*...*/});

var Content = Ractive.extend({
    template: '#template-content',
    components: {
        //view: views['list']
    },
    onrender: function() {
        /* call this.request */
    },
    request: function(route) {
        var self = this;
        $.ajax({
            url: route,
            type: 'GET',
            data: {},
            dataType: 'json',
            success: function(data){
                self.components.view = views[data.view];
            }
        });
    }
});

Ajax请求返回{view:'list'}。我在控制台中写道:“Content.components.view”并看到:

function ( options ) {
    initialise( this, options );
}

但是“Content.findComponent('view')”返回“null”。

如果我在组件中取消注释“// view:views ['list']”行,它将起作用。如何动态更改组件?

更新1:

我以为我可以这样做:

var Content = Ractive.extend({
    components: {
        // Aaaand add listener for data.view?
        view: function(data) {
            return views[data.view];
            // But no, it is not updated when changes data.view ...
        }
    },
    data: {},
    oninit: function() {
        var self = this;
        self.set('view', 'list');
    },
});

不工作..为什么然后需要“数据”参数?

1 个答案:

答案 0 :(得分:0)

我赢了:)

// Create component globally
Ractive.components.ListView = Ractive.extend({});

// Create ractive instance
var Content = Ractive.extend({
    template: '#template-content',
    partials: {
        view: 'Loading...' // So... default
    },
    oninit: function() {
        var self = this;
        $.ajax({
            ...
            success: function(data){
                // Hardcore inject component
                self.partials.view = '<'+data.view+'/>';

                // Little hack for update partial in template
                self.set('toggle', true);
                self.set('toggle', false);
            }
        });
    },
});

在内容模板中:

{{^toggle}}{{>view}}{{/}}

它的作品 - 烟火!