在Ember中异步加载局部视图

时间:2014-04-08 01:57:51

标签: ajax asynchronous ember.js

我创建了一个Ember助手,允许从服务器上的URL加载动态生成的局部视图。它看起来像这样:

Ember.Handlebars.helper('serverPartial', function(url, options) {
    var template;

    $.ajax(url, {
        async: false,
        success: function(templateText){
            template = Ember.Handlebars.compile(templateText);
        }
    });

    template(this, options);
});

它是从父Handlebars模板调用的,如下所示:

{{serverPartial templateUrl}}

正如您所看到的,从服务器检索模板的ajax调用是同步调用,因为我无法找到任何其他方式来返回Ember框架所期望的模板内容。不幸的是,这种同步调用阻止了整个父模板的渲染。

有没有办法返回模板的承诺,或者允许部分视图异步或独立加载的任何其他方式?

2 个答案:

答案 0 :(得分:3)

感谢小费,@ Rajat。我最终使用Views来完成此任务。我创建了一个最初加载默认子模板的视图容器,然后该子容器在插入后从服务器加载实际内容。这是我采取的方法:

App.LoadingView = Ember.View.extend({
    didInsertElement: function(){
        var container = this._parentView;
        $.get('http://server/serverTemplate', function(data){
            container.pushObject(Ember.View.create({
                template: Ember.Handlebars.compile(data)
            }));
            container.removeObject(container.get('loadingView'));
        });
    },
    template: Ember.Handlebars.compile('client awesome')
});

// inherit from ContainerView and initialize with default content
App.SnippetView = Ember.ContainerView.extend({
    childViews: ['loadingView'],
    loadingView: App.LoadingView.create()
});

我确信有更好的方式来表达这一点,但至少可以完成工作。

答案 1 :(得分:2)

首先,你试图用Handlebars助手做的事情不是他们想要做的。 Handlebars helpers是严格的标记格式化程序,应该用于简单的HTML调整。

其次,在典型的ember应用程序中,您要做的事情永远不会完成。没有“按需”获取模板。

这是因为当应用加载并在客户端上运行时,所有模板都会在一次扫描中下载。它们预编译为JavaScript函数,并在Strings哈希中存储为Ember.Handlebars

在应用加载时下载它们,然后在呈现视图时进行评估。与此同时,他们只是Strings

现在,如果您仍想做您正在做的事情,我建议您尝试在Views中执行此操作。

相关问题