documentcloud/backbone — pull request #707 by braddunbar (2011-10-31 11:53:57+00:00)
Title: implement callbacks as linked list

While writing a patch for #683 I thought that it would be easier to deal with issues like it if event callback lists were implemented as a linked list rather than an array. I think this simplifies the implementation in two ways:

1. __Sparseness__: By using a linked list, callbacks can be removed from the list during `unbind` without creating "holes" in the list. This means that the performance of `trigger` and `unbind` is not affected by these holes, and we don't have to deal with filling them up during iteration.
2. __Indicies__: Since no array indicies need to be kept up with (i.e. the index of the callback being executed and the length of the list) no bookkeeping needs to be done in dealing with issues like #683. This reduces the size of the code significantly.

It should be noted that events will behave slightly differently in regard to newly added callbacks: In the array implementation, the array length is cached before firing any callbacks. Therefore, callbacks that are bound during a call to `trigger` will not be fired unless trigger fills in a hole during invocation, thus skipping an earlier callback and firing a new one instead. In this implementation newly bound callbacks will always be fired since they will just be appended to the end of the linked list.