mikeric/rivets — pull request #121 by bemson (2013-02-03 07:56:46+00:00)
Title: Reuse bindings to avoid redundant node parsing and pub/sub events

This PR proposes to solve a minor issue, when using rivets in an shared component environment: redundant pub/sub events.

While my components invoke `.unbind()` well, I still have to manage where they bind to the DOM. Otherwise, duplicate bindings would access the same model several times. I felt binds could be managed to avoid redundant events, wasted processor cycles, and (perhaps) concurrency issues.

My solution was to _cache_ bindings in their corresponding DOM element, and then allow any number of views to use them. The first `rivets.bind()` call handles the initial node parsing, and then stores these bindings in a "_rivets" property. Subsequent calls then reference this binding cache, instead of parsing elements again. I then track which views are using the cache, so as to determine when it can be removed.

I've added a single rspec test, which passes but could likely be expanded upon.

#### Considerations

This approach does introduce complexity, but it has also offset the pain from managing bind targets. While the rspecs pass, there are applications of rivets (however, unwise) that this cache scheme would break:

1. Binders that include the "owning" view in their logic.
1. Rebinding an element, after changing it's data-attributes.
2. Rebinding with different model(s) and/or model aliases/keys.

Also, though we all read data from the DOM, some folks wince at storing objects in it. Likewise, storing a binding to it's element is a circular reference which _might_ be a problem.