简体   繁体   English

EmberJS在控制器中的承诺

[英]EmberJS promises in controllers

I've been trying for hours to figure out why this isn't working, but I just can't seem to find a solution. 我已经尝试了好几个小时才能弄清楚为什么它不起作用,但是我似乎找不到解决方法。

I'm trying to get data via REST, do a few things with the data (eg filter it) and then return the results. 我试图通过REST获取数据,对数据做一些事情(例如过滤),然后返回结果。

This works perfectly if I just return the this.store.find('somthing') . 如果我只返回this.store.find('somthing')这将完美地工作。 As soon as I use then() - everything breaks. 一旦使用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')

});

Errors in console: 控制台错误:

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 

It sounds like in your song template you are using an {{#each ...}} which tells ember you are iterating over some array, but it's finding something that isn't an array. 听起来您的歌曲模板中使用的是{{#each ...}},它告诉ember您正在某个数组上进行迭代,但是它发现的不是数组。

You can setup your SongController to be an ArrayController 您可以将SongController设置为ArrayController

App.SongController = Ember.ArrayController.extend()

and return the data from the model hook 并从模型挂钩返回数据

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);
   }
});

If you really want it to be a computed property just return the promise from the find, it's an arrayproxy that will populate once it's resolved (so it will initially be 0, but once the server's responded it will grow). 如果您真的希望它是一个计算属性,则只需从查找中返回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