documentcloud/backbone — Issue #889: Enhance the way we reference a view's sub-elements
Author: gschammah
Created: 2012-01-24 21:37:00+00:00
State: open

It is common for me while working in a backbone project to access my views' sub-elements many times. Here I put a simple example:

```javascript
var myView = Backbone.View.extend({
el: '#myDiv',

hideButton: function() {
this.$('#myButton').hide();
},

showButton: function() {
this.$('#myButton').show();
}
});
```

This works fine, but if the button id changes in the future, then I have to change that id in to places in my view (a real project will demand even more changes). So what I always end up doing is something like this:

```javascript
var myView = Backbone.View.extend({
el: '#myDiv',

_initialize_elements: function() {
this.elements = {
myButton: this.$('#myButton')
};
},

initialize: function() {
this._initialize_elements();
},

hideButton: function() {
this.elements.myButton.hide();
},

showButton: function() {
this.elements.myButton.show();
}
});
```

For me this approach is fine, but I don't like to manually initialize every view every single time to store the jQuery reference to each of my view's sub-elements, and also is very easy to forget to do it.

I think the best approach would be for a Backbone view to have an 'elements' object that works in a similar way than the 'events' object.

E.g.:

```javascript
var myView = Backbone.View.extend({
el: '#myDiv',

elements: {
myButton : '#myButton'
},

hideButton: function() {
this.elements.myButton.hide();
},

showButton: function() {
this.elements.myButton.show();
}
});
```

Then, before the 'delegateEvents' function is called in Backbone.View constructor, we can replace the value of each 'elements' key a jQuery object. I will request for a pull request soon. I would love to hear your comments.

Thanks,
Gabriel