I have a Marionette view that has the following code:
onRender: {
$('#someDiv').find('a').click(function(){
// some code here
});
}
But I want to refactor to something like this:
events: {
'click [selector here]': 'executeCode'
},
executeCode: function() {
// some code here
}
Is this possible?
That's actually the recommended way of binding DOM event handlers in Backbone. Backbone uses jQuery
onmethod (event delegation syntax) for binding the event handlers behind the scenes.Please note that the event handlers work for matching descendants of the View's element. If
#someDivis not a descendant of the View's element then the event handler won't work.It should also be noted that
thisin the context of the handler refers to the View object not the target element of the event:The above snippet works like the following snippet: