tfrydrychewicz / aurelia-flux

Flux dispatcher plugin for Aurelia
MIT License
74 stars 17 forks source link

How to deal with stores being registered after something is dispatched? #19

Open viniciusoyama opened 8 years ago

viniciusoyama commented 8 years ago

Hi everyone, I need some advice (I don't know if here is the best place to ask). I'm trying to modify the app from this article:

blog.durandal.io/2015/08/07/creating-reactive-loosely-coupled-apps-with-aurelia-and-flux-episode-2/

I'm trying to load some Todos based on some params from the route. So on the List view I'm loading the todos via ajax on the activate method:

  activate(params) {
    return this.http.fetch(`/api/todos.json?year=${params.year}&month=${params.month}&day=${params.day}` )
      .then(response => response.json())
      .then(timeEntries => this.dispatcher.dispatch('list.load', timeEntries));
  }

and the todo-list.store is decorated to handle the 'list.load' action as well. The problem is that the ajax request is made and resolved BEFORE the todo-list.store instantiates and registers itself for the 'list.load' action. I don't think that I should put the ajax request on the store. Even if I do it will not help because it won't have the params to send to the server.

I came up with two solutions:

1) Put the ajax on the attached() callback method on the ViewModel. It will work because this method is called after the store is instantiated but I don´t think that is the correct solution because there is edge cases where I can have 2 siblings custom elements/VM that uses the same store. If the first is atached and the attached() method dispatches something the second store on the second VM will not trigger the callback yet because it is not registered/instantiated.

2) Modify the lib in order to make the dispatcher wait for all aurelia's rendering stuff finishes

Am I missing something? What should I do in this case?

Thanks!

airboss001 commented 8 years ago

The way I approached this was that I considered my store persistent and global to the app. In my case as well when the store was constructed it would load saved data from the localstorage to populate its data.

I did this in the app.js file where I injected them through the constructor and basically just threw away the reference there, but the singleton was created. That guaranteed that the store is loaded and waiting when the VMs are constructed/activated/attached for the views.