Saturday, 17 August 2013

Pattern for caching a View's sub-elements in Backbone.js

Pattern for caching a View's sub-elements in Backbone.js

Moving from a framework-less world to Backbone.js, I've brought along the
practice of "caching" my jQuery objects by always storing a reference to
them (for efficiency).
var myCachedEl = $('#element');
myCachedEl.on('click', function() {
myCachedEl.html('That tickles.');
});
In Backbone, this is how I might cache my jQuery objects:
var RandomView = Backbone.View.extend({
intitialize: function() {
this.$lastRoll = this.$el.find('#last-roll');
this.listenTo(this.model, 'change', this.render);
},
render: function() {
this.$lastRoll.html(this.model.get('lastRoll'));
},
events: {
'click #last-roll': function() {
this.model.roll();
}
}
});
var randomView = new RandomView({
el: '#random-view',
model: random
});
Given my current setup, I would like to do something akin to...
events: {
'click this.$lastRoll': function() {
// ...
}
}
...where, in my events, I could bind a click event to a cached element.
However, the above syntax does not work. I suspect there may be some way
to "officially" define sub-elements, so that I could use some syntax akin
to what is above.
Question: Is there a "better," "cleaner," or more "Backbone-semantic"
pattern, for caching my View's sub-elements, that I could/should follow,
instead of my current pattern?

No comments:

Post a Comment