AJAX promise without Ember Data

前端 未结 3 923
夕颜
夕颜 2020-12-07 15:00

I have decided to not use ember-data as it\'s not production ready and still changing. My app only needs to make a few ajax requests anyway so it shouldn\'t make too big of

3条回答
  •  难免孤独
    2020-12-07 15:42

    I'd use Ember.Deferred instead of returning an empty array as mentioned before.

    App.User.reopenClass({
      getAllUsers: function() {
        var dfd = Ember.Deferred.create();
        var users = [];
    
        $.ajax({
            url: "/api/get_users",
        }).then(function(response) {
            response.forEach(function(user){
                var model = App.User.create(user); 
                users.addObject(model);
            });
            dfd.resolve(users);
        });
        return dfd;
      }
    });
    

    In your model hook all you have to do is this

    model: function(){
      return App.User.getAllUsers();
    }
    

    Ember is smart enought and knows how to handle the promise you return, once it's resolved the model will be correctly set, you can also return a jQuery promise but it will give you some weird behavior.

提交回复
热议问题