EmberJS承诺在控制器中

时间:2013-11-29 16:20:19

标签: javascript ember.js

我一直在努力弄清楚为什么这不起作用,但我似乎无法找到解决方案。

我正在尝试通过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 

1 个答案:

答案 0 :(得分:0)

听起来好像在你的歌曲模板中你正在使用{{#each ...}}来告诉你,你正在迭代一些数组,但是它找到的东西不是数组。

您可以将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')