【问题标题】:Render a template with model outside of rootElement with Ember.js使用 Ember.js 在 rootElement 之外渲染带有模型的模板
【发布时间】:2013-09-12 23:56:25
【问题描述】:

我正在将 Ember.js 添加到现有的 Rails 应用程序中,并在创建 Ember.Application 时使用 rootElement 选项。

rootElement 之外的几个地方我想插入一个小 ember 模板,该模板绑定到一个简单的 Ember.Object 模型。

我创建了一个带有示例的 jsfiddle,我希望它可以使我正在寻找的内容变得清晰:http://jsfiddle.net/amiel/x9fCz/2/

最好的方法是什么?

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    我创建了一个new ember view,模板名称与我的车把模板匹配。然后在 ember 初始化程序中实例化它。

    Ember.Application.initializer({
      name: "clock_view",
      initialize: function(container, application) {
        var view = App.ClockView.create();
        view.replaceIn('#now');
      }
    });
    

    查看 jsfiddle 上的完整示例:http://jsfiddle.net/amiel/2FsxA/1/

    我不会接受我自己的答案,只是看看其他人是否有更好的方法来做到这一点。

    更新:这是另一种可能的解决方案:http://jsfiddle.net/amiel/2FsxA/3/

    TL;DR:

    App.ApplicationRoute = Ember.Route.extend({
        setupController: function(controller, model) {
            this.setupClock();
            this._super(controller, model);
        },
        setupClock: function() {
            var view = App.ClockView.create();
            view.replaceIn('#now');
        }
    });
    

    【讨论】:

    • 这似乎是一个相当不错的解决方案!很干净。唯一的缺点是放置视图的代码不在您的“正常”位置,其他开发人员会搜索它。
    • @JordyLangen 谢谢!是的,我同意。这似乎只比在Ember.Application.create({ ready: ... 中包含此视图相关代码稍好。也许ApplicationRouterApplicationController 中有一个钩子会更好?
    • 弃用:不再支持使用 defaultContainer。 [默认容器#lookup]。你应该检查这个以使这项工作在最后的 Ember 中顺利进行gist.github.com/stefanpenner/5627411
    【解决方案2】:

    为了防止出现DEPRECATION: Using the defaultContainer is no longer supported 消息,您必须在 ApplicationView#didInsertElement 中创建一个 childView。

    App.ApplicationView = Ember.View.extend({
        didInsertElement: function() {
            var view = this.createChildView(App.ClockView);
            view.replaceIn('#now');
        }
    });
    

    App.ClockView#controller 现在也将成为 App.ApplicationController。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多