javascript - Ember.js - 模型中的异步调用 find() 方法

标签 javascript ember.js

我已经在我的 Property 模型上实现了 find()findAll() 方法。这两种方法都对 API 进行异步调用。 findAll() 在连接我的家庭路线的导出时被调用,并且工作正常。 find() 由 Ember.js 在连接我的属性路由的导出时调用。请注意,当通过操作导航到属性路由时不会调用 find(),但会在您通过 URL 直接转到路由时调用。

这是我的路由器:

App.Router = Ember.Router.extend({
    root: Ember.Route.extend({
        showProperty: Ember.Route.transitionTo('property'),
        home: Ember.Route.extend({
            route: '/',
            connectOutlets: function(router) {
                router.get('applicationController').connectOutlet('home', App.Property.findAll());
            }        
        }),
        property: Ember.Route.extend({
            route: '/property/:property_id',
            connectOutlets: function(router, property) {
                router.get('applicationController').connectOutlet('property', property);
            }
        }),
    })
});

这是我的findAll()find() 方法:

App.Property.reopenClass({
    find: function(id) {
        var property = {};
        $.getJSON('/api/v1/property/' + id, function(data) {
            property = App.Property.create(data.property);
        });
        return property;
    },
    findAll: function() {
        var properties = [];
        $.getJSON('/api/v1/properties', function(data) {
            data.properties.forEach(function(item) {
                properties.pushObject(App.Property.create(item));
            });
        });
        return properties;
    }
});

当我转到索引以外的路由时,例如 http://app.tld/#/property/1,该路由被重写为 http://app。顶级域名/#/属性/未定义。没有任何内容被传递到 Property Controller 的 content 属性。如何在 find() 方法中进行异步调用?除非我弄错了,异步调用在 findAll() 方法中工作正常,这是我困惑的根源。

这个问题类似于Deserialize with an async callback ,但我使用的是 find() 方法,而不是重写 deserialize() 方法。

提前致谢。

最佳答案

我发现设置 id 属性可以明确解决这个问题。在您的情况下,这看起来像这样。

find: function(id) {
  var user = App.User.create();

  $.getJSON('/api/v1/property/' + id, function(data) {
    user.setProperties(data.user)
  });

  user.set("id",id); // <-- THIS

  return user;
}

一旦您的用户 获得其属性,就可以正常设置 View 更新。 Ember 之前只需要 id 部分来更新 URL。

希望这有帮助:-)

关于javascript - Ember.js - 模型中的异步调用 find() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12064076/

相关文章:

javascript - 在 Handlebars.js 中引用数组项

javascript - Angular Controller 中的事件仅触发一次

javascript - 我可以在 Ember 2.1 中升级 jQuery 2 吗?

ember.js - 如何在 EmberJS 中设置可观察但在少数情况下不运行可观察函数的属性

javascript - 使用 Promise 返回多个查询

javascript - 是否可以在 getRange() 中使用单元格引用作为行/列位置?

javascript - 识别Javascript对象中的 "Class Name"

javascript - Ember Actions 冒泡流

ember.js - emberjs + ember-data 子资源

ember.js - Emberjs 开发一个与其自己的路由/状态隔离的组件,可以将其集成到主应用程序中