Ember.js - 调用父模型钩子来加载子数据

时间:2014-02-13 10:08:40

标签: javascript ember.js model router ember-router

我在Ember有一个主/详细视图。如果我直接调用详细信息页面,详细信息页面的模型钩子需要来自父(主)的模型(数据)。调用详细模型钩子 - 什么是获取/调用模型的正确方法,因此详细信息钩子中的modelFor函数可以工作。

路由器:

App.Router.map(function(){
    this.resource('index', { path: '/' } );
    this.resource('devices', { path: '/devices'}, function() {
        this.resource('device', { path: ':imei'});
    });
});

主路线:

App.DevicesIndexRoute = Ember.Route.extend({
    model: function() {

        var self = this;
        return requestController.get({
            url: "foo/bar/",
            success: function(data) {
                console.log(data);
                return data;
            },
            error: function() {
                console.log("error");
                return [];
            }
        });
    }
});

详细路线:

    App.DeviceRoute = Ember.Route.extend({
        model: function(args) {
////// Gets Called - needs data from master!!
            var model = this.modelFor('devices.index').findBy('imei', args.imei);
            return model;
        }
    });

感谢您的帮助

1 个答案:

答案 0 :(得分:5)

devices.index路由不是父路由,而是另一条路由。通常,您将在资源路由上定义模型,然后通过叶子路径进行访问:

App.Router.map(function(){
    this.resource('index', { path: '/' } );
    this.resource('devices', { path: '/devices'}, function() {
        this.route('device', { path: ':imei'});
    });
});

主路线:

App.DevicesRoute = Ember.Route.extend({
    model: function() {

        var self = this;
        return requestController.get({
            url: "foo/bar/",
            success: function(data) {
                console.log(data);
                return data;
            },
            error: function() {
                console.log("error");
                return [];
            }
        });
    }
});

索引路线:(在未来的ember版本中,这将自动获取父模型)

App.DevicesIndexRoute = Ember.Route.extend({
    model: function() {
        this.modelFor('devices');
    }
});

详细路线:

App.DevicesDeviceRoute = Ember.Route.extend({
    model: function(args) {
        var model = this.modelFor('devices').findBy('imei', args.imei);
        return model;
    }
});