Proper techniques for allowing many views to subscribe to window.unload? I would like to execute code for many views whenever the window is unloaded.

For instance, I could have something like this in a view's initialize:

initialize: function() {
    $(window).unload(this.stopListening.bind(this));
}


I'm wondering if it would be better to have a manager which aggregates all of the view's requests into one event like:

define(function () {
    'use strict';

    var ForegroundViewManager = Backbone.Model.extend({

        defaults: function () {
            return {
                views: []
            };
        },

        initialize: function() {
            $(window).unload(function () {
                this.allViewsStopListening();
            }.bind(this));
        },

        allViewsStopListening: function() {
            _.each(this.get('views'), function(view) {
                view.stopListening();
            });
        },

        subscribe: function (view) {
            var views = this.get('views');
            var index = views.indexOf(view);

            if (index === -1) {
                views.push(view);
                console.log("Subscribed a view:", view, views.length);
            } else {
                console.log("Already subscribed!");
            }
        },

        unsubscribe: function (view) {
            var views = this.get('views');
            var index = views.indexOf(view);

            if (index &gt; -1) {
                views.splice(index, 1);
            }
        }

    });

    return new ForegroundViewManager();
});


The second way is a lot more code, but results in just one unload event being bound to the window and then iterating over a collection. Is this preferred? Or is it better to have each view bind itself to window.unload?
An opinion question, always tricky;

I think we can all agree that the second approach is not KISS and requires more bandwidth to download to the browser. As far as I can tell, this will not save any memory either..

I would strongly suggest to use the first approach.

Furthermore:


unsubscribe could be reduced to:

unsubscribe: function (view) {
  this.get('views') = _without( this.get('views') , view );
}

Production code should not use console.log
subscribe could use _.union()
subscribe could be reduced to:

subscribe: function (view) {
  this.get('views') = _union( this.get('views') , view );
}