Emberjs:动态模板嵌套和路由

Emberjs: Dynamic template nesting and routing

本文关键字:嵌套 路由 动态 Emberjs      更新时间:2023-09-26

我今天大部分时间都在努力解决这个问题,这让我发疯了,因为我觉得我已经快到了,但就是想不出最后一部分。。。

我有一个名为Map的路径,它呈现一个侧边栏,其中有一个用于侧边栏内容的命名出口:

map.hbs:

<div id="map-container">
    {{render sidebar}}
    <div id="map-canvas">
    </div>
</div>

sidebar.hbs:

<div id="content-menu">
    {{outlet sidebar-content}}
</div>

我的侧边栏中的每个菜单项都有一个名为loadModule的自定义操作,该操作将命名视图呈现到侧边栏内容出口中(使用{{action‘loadModule’‘sideband.module’}}):

var MapRoute = App.AuthenticatedRoute.extend({
actions: {
    loadModule: function(module) {
        //load a valid view template into the view
        this.render(module, 
            {
                into: 'sidebar',
                outlet: 'sidebar-content'
            });
    }
}
});
module.exports = MapRoute;

控制器中该视图的任何操作都可以正常工作,我可以通过按钮等触发它们,也可以在边栏模块视图中的didInsertElement中调用它们。

我的问题是,我不能为这些视图定义一个模型,所以如果我尝试在它们的任何控制器中从我的API获取数据,它不会将数据呈现到模板中。

我尝试使用链接到,但我无法将模板附加到当前视口,而不是刷新整个页面,这与使用侧边栏(我不希望更改路线)的意义不同

var SidebarUserController = App.ApplicationController.extend({
actions: {
    doSomething: function() {
        alert('SOMETHING');
    },
    fetchUserProfile: function() {
        //do something
        var mod = this.store.find('profile', App.Session.get('uid'));
    }
}
});

一旦渲染模板,我就可以从渲染模板中触发其中任何一个操作,但是,尽管我的存储会随记录更新,但侧边栏/user.hbs中的手把助手不会填充模型数据。

这是我的型号:

var Profile = DS.Model.extend({
uid: DS.attr('string'),
firstName: DS.attr('string'),
lastName: DS.attr('string'),
gender: DS.attr('string'),
DOB: DS.attr('date'),
email: DS.attr('string')
});
module.exports = Profile;

这是我的侧边栏/user.hbs:

<div class="container">
    <button {{action 'doSomething'}}>Do A Thing</button>
    <h1>{{firstName}} {{lastName}}</h1>
    <h4>{{id}}</h4>
    {{#if isAuthenticated}}
        <a href="#" {{action 'logout'}}>Logout</a>
    {{/if}}
</div>

在该模板中,firstName、lastName和id字段不会填充,即使我从API中提取数据并成功存储它

此外,如果有帮助的话,我的侧边栏/用户的router.map看起来是这样的:

this.resource('sidebar', function() {
        this.route('user');
    });

我认为这里的根本问题是,如果不触发路由,我就无法为控制器设置模型。我做错了吗?

好的,所以我已经为我的特定实例解决了这个问题。这可能不是最好的方法,但这正是我需要的:

在我的MapRoute中,我在setupController函数中为我的附加侧边栏菜单设置了模型和控制器。这样做允许我在页面加载中加载关键数据(如用户配置文件等),并且我仍然可以保留Route中每个侧边栏模块的渲染功能,这将允许加载初始数据,并且仍然允许我在后续功能上更新每个侧边栏模块控制器的模型数据:

map_route.js:

actions: {
        loadModule: function(module) {
            this.render(module, {into: 'sidebar', outlet: 'sidebar-content'});
        }
},
setupController: function(controller, profile) {
    var model = this.store.find('profile', App.Session.get('uid'));
    var controller = this.controllerFor('sidebar.user');
    controller.set('content', model);
},
...