foodcoops/foodsoft — pull request #183 by JuliusR (2013-10-03 13:36:27+00:00)
Title: Publish subscribe ajax

- [ ] Discuss the publish/subscribe pattern: Is it useful?
- [ ] Update locales
- [ ] Testing

# The problem: wrong controller
## `StockArticle` manipulation in `Delivery` form

The changes in foodcoops#141 made it easier to create a delivery because the user can create and update `StockArticles` in the delivery form. However, a probably bad practice was used: All the `StockArticle` manipulation was done in the `Deliveries` controller. Here I would like to suggest a new pattern in order to

* move the `StockArticle` manipulation to the correct controller
* provide an easy way to perform the DOM updates in the current view (`Deliveries`, `StockArticles`, ...).

## More use cases
I am planning to provide similar features for `StockArticles` in the `StockTaking` form, so there is the need of at least one more application of this pattern in the future.

# How it could work (my suggestion)
Let us assume the current view is `views/deliveries/new.html.haml` and we would like to create a new `StockArticle`.

1. AJAX request (GET) to `StockArticle#new`
* open a modal by `views/stockit/new.js.erb`
2. AJAX request (POST) to `StockArticle#create`
* display a universal success message by `views/stockit/create.js.erb` and do `$('body').trigger('StockArticle#create', ...)` passing the new `StockArticle`'s id
3. the `.trigger(...)` causes another AJAX request (GET) to `Delivery#on_stock_article_create`
* handle the DOM update by `views/deliveries/on_stock_article_create.js.erb`

# Disadvantages of this approach
* Readability: Is it clear what is going on?
* Two subsequent AJAX requests for one creation/update
* Still some redundancy in those controllers which use the function in their views (see actions named `on_stock_article_create`, `on_stock_article_update` etc.)

# Question to you
Would you be fine if I followed this approach to the end? Do you have some experience in that and/or a better idea?