繁体   English   中英

EmberJS在控制器中的承诺

[英]EmberJS promises in controllers

我已经尝试了好几个小时才能弄清楚为什么它不起作用,但是我似乎找不到解决方法。

我试图通过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 

听起来您的歌曲模板中使用的是{{#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);
   }
});

如果您真的希望它是一个计算属性,则只需从查找中返回promise,它是一个arrayproxy,它将在解析后填充(因此最初将为0,但是一旦服务器响应,它将增长)。

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

  return promise;
}.property('second')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM