检测模型更新时间并在Emberjs中发送Ajax请求

时间:2013-10-14 08:24:55

标签: ember.js ember-data

在我的应用程序中,我有模型,我想在模型更新时将ajax请求发送到服务器。例如,我有一个这样的模型:

App.Post = DS.Model.extend({
  title:DS.attr('string'),
  comment:DS.attr('string')
});

和这样的控制器:

App.PostController = Ember.Controller.extend({
   //if post model update send Ajax Request 
});
App.CommentController = Ember.Controller.extend({
  //if post model update send ajax Request
});
App.OtherController = Ember.Controller.extend({
 //if post model update send ajax Request
});

1 个答案:

答案 0 :(得分:0)

您可以在路线中定义一个动作

App.ApplicationRoute = Ember.Route.extend({
    actions:{
        sendRequest:function(){
            //send Ajax Request
        }
    }
});

并在您的邮政路线的setupController挂钩中订阅模型事件

App.PostRoute = Ember.Route.extend({
  setupController: function(controller, model) {
    controller.set('model', model);
    model.on('didUpdate',controller,function(){this.send('sendRequest')})
    model.on('didCreate',controller,function(){this.send('sendRequest')})
    model.on('didDelete',controller,function(){this.send('sendRequest')})
  }
});

希望这个帮助,这只是一个例子,你可以通过多种方式实现它,想法是订阅当服务器响应POST,PUT或DELETE请求时触发的模型事件

基于你的JsBin ......

OlapApp.OlapRoute = Ember.Route.extend({
    setupController(controller,model){
    var that = this;
      this.store.findAll('axisModel').then(function(axisModel){
        axisModel.on('didUpdate',controller,function(){this.send('sendRequest')})
        axisModel.on('didCreate',controller,function(){this.send('sendRequest')})
        axisModel.on('didDelete',controller,function(){this.send('sendRequest')})
        that.controllerFor('OlapColumn').set('model', axisModel);
        that.controllerFor('OlapRow').set('model', axisModel);
        that.controllerFor('OlapFilter').set('model', axisModel);
        });
    }
});