本文介绍了灰烬初始化带有查询的路由模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用DS查询初始化路线模型,如下所示

I am trying to initialize a Route's model with a DS query, as follows

App.Router.map(function() {
    this.resource('post', { path: '/posts/:post_slug' });
});

App.PostsRoute = Ember.Route.extend({
    model: function(params) {
        var records = App.Post.find({ slug: params.post_slug });
        return records.get('firstObject');
    }
});

在这里,我找到了一个子弹,然后将第一个结果设置为路线模型。但是由于记录是异步填充的,因此模型数据的设置不正确。正确的方法是什么?

Here, i find a Post by its slug and set the first result as the route model. but since records is populated asynchronously, the model data is not set properly. What is the correct way to do this?

推荐答案

使用Deferred模式解决了此问题。

Solved this with Deferred pattern.

App.PostsRoute = Ember.Route.extend({
    model: function(params) {
        var records = App.Post.find({ slug: params.post_slug });
        var promise = Ember.Deferred.create();
        records.addObserver('isLoaded', function() {
            promise.resolve(records.get('firstObject'));
        });
        return promise;
    }
});

这篇关于灰烬初始化带有查询的路由模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 01:06