简体   繁体   中英

Passing current router's model into a created object in Ember.js

I'm building an object that handles a timing method to control refreshing a model with data from the server. It's extremely simple. However, I'm having to redefine the refresh object inside the router where I'm instantiating it with the current model. Which defeats the point of making it a seperate object. My intention is to use it on multiple pages.

I start with the object as such:

App.ModelRefresh = Ember.Object.extend({
  init: function(callback) {
    this.timer = setInterval(this.refresh.bind(this), App.POLL_INTERVAL);
    this._super();
  },
  stop: function(){
    console.log('stop');
    clearInterval(this.timer);
  },
  refresh: function(){
    console.log('refreshing');
  }
});

And then create it within a router to handle reloading. Again like so:

App.PublishablesRoute = Ember.Route.extend({
  model: function() {
    return App.Publishable.fetch();
  },
  setupController: function(controller, model) {
    controller.set('model', model);

    var modelRefresh = App.ModelRefresh.create('something');
    this.set('modelRefresh', modelRefresh );

    modelRefresh.refresh = function() {
      model.reload();
    };
  },
  deactivate: function() {
    this.get('modelRefresh').stop();
  }
});

What I would like to do instead of modifying the modelRefresh , and adding the current model.reload() , is to have the Object get the current model's router when instatiated. I've tried passing it as a callback but it simply doesn't work.

Any ideas would be helpful.

I'd probably build up some sort of scheduler whose purpose was to handle the reloading, scheduling etc.

Then you could subscribe to the reloader and unsubscribe when it's time to stop it. Then you can avoid having a model in multiple places reloading.

Or I'd add the logic to a mixin then add that mixin to your models so you could call, model.startReloading(2000) etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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