chrismccord/sync — pull request #93 by wursttheke (2014-02-12 13:34:59+00:00)
Title: Cancel subscription channel when partial is destroyed

Hi Chris!

I came across a JS-issue when trying to remove a partial from the page, which has been removed and readded before. It sounds confusing, I know. :smile:

Well, it's a bit of an edge case. Here's what happens:

1. Add partial to the page
2. Remove it from the page
3. Add it again
4. Trying to remove it again creates a JS-Error

The error in step 4 results from the destroy-subscription still hanging around from step 1. The destroy message coming in on step 4 will then find the old subscription and try to remove the old DOM element, which of course has already been removed in step 2.

To solve this, the subscribe method on the ```Sync.Faye``` and ```Sync.Pusher``` Class now returns a subscription object, either ```Sync.Faye.Subscription``` or ```Sync.Pusher.Subscription```, which is then stored in the partial and can later be used to automatically unsubscribe from the channel by calling ```cancel()``` on it when the partial is destroyed.

Why does one need this?

I'm currently working on an addition to scopes. It will allow you to explicitly define named syncing scopes on the model with the help of ActiveRecord Relations. In contrast to the normal procedure of adding/removing partials only when records are created/destroyed, this approach also needs to add and remove them when certain attributes on the record have changed. This may lead to the need of adding/removing records multiple times, depending on the use case of course.

I tested this patch with a Faye setup and it works fine. Maybe someone can confirm it works with Pusher as well.

Let me know, what you think. And again, thanks for the awesome gem!