【问题标题】:EmberJS promises in controllers控制器中的 EmberJS 承诺
【发布时间】:2013-12-15 21:24:23
【问题描述】:

我已经尝试了几个小时来弄清楚为什么这不起作用,但我似乎无法找到解决方案。

我正在尝试通过 REST 获取数据,对数据执行一些操作(例如过滤它),然后返回结果。

如果我只返回this.store.find('somthing'),这将非常有效。一旦我使用then() - 一切都会中断。

App.SongController = Ember.ObjectController.extend({

  first: (function() {
    return this.second();
  }).property('first', '').volatile()


  second: (function() {
    var promise = Ember.Deferred.create();
    var data = [{ id: 1, name: 'hi' }];

    this.store.find('something').then(function (data) {
      // Do something with the data..

      // return the data
      promise.resolve(data);
    });

    return promise;
  }).property('second')

});

控制台错误:

Assertion failed: The value that #each loops over must be an Array. You passed <Ember.Deferred:ember350>
Uncaught TypeError: Object [object Object] has no method 'addArrayObserver'
Assertion failed: Emptying a view in the inBuffer state is not allowed and should not happen under normal circumstances. Most likely there is a bug in your application. This may be due to excessive property change notifications.
Uncaught Error: You cannot modify child views while in the inBuffer state 

【问题讨论】:

  • 我认为在某些路由模型中你返回songController.first() 或songController.second(),你能显示那个代码吗?

标签: javascript ember.js


【解决方案1】:

听起来您在歌曲模板中使用了 {{#each ...}},它告诉 ember 您正在迭代某个数组,但它找到的不是数组。

您可以将 SongController 设置为 ArrayController

App.SongController = Ember.ArrayController.extend()

并从模型钩子返回数据

App.SongRoute = Em.Route.extend({
   model: function(){
      return this.store.find('something');
   },
   setupController: function(controller, model){
     // and if your need to modify the data, it'll be loaded by this point
     model.blah = 123123;
     // then let ember finish off setting up the controller
     this._super(controller, model);
   }
});

如果您真的希望它是一个计算属性,只需从 find 中返回 promise,它是一个 arrayproxy,一旦它被解析就会填充(所以它最初是 0,但是一旦服务器响应它就会增长)。

second: function() {
  var promise = this.store.find('something').then(function (records) {
    records.objectAt(0).set('someValue', false);
  });

  return promise;
}.property('second')

【讨论】:

  • 这对我来说不太适用。我正在尝试获取“类别”,然后将它们循环到获取“类别 ID”,然后使用这些 ID 构建对“项目”表的另一个查询,然后我返回并在视图中循环。所以基本上我想返回一个嵌套的then 语句(find('category').then(function(data){ return findQuery('item', {some: attrs}) }))。知道如何做到这一点吗?
猜你喜欢
  • 2015-12-30
  • 1970-01-01
  • 2017-12-14
  • 2018-04-08
  • 2014-06-04
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多