Bind Events To All Text Input Fields In All Backbone Views
Solution 1:
Hi I wrote my tipp in coffe script because it is simpler.
You can use a mechanism similar to ruby mixins. Then create a mixin with your common behaviour. Then mix the concern into a class which extends Backbone.View. Then use your base view class in all places as base for your view classes.
This is the mixesIn underscore function:
_.mixin
mixesIn: (base, mixins...) ->
class Mixed extends base
for mixin in mixins by -1
for name, method of mixin::
Mixed::[name] = method
Mixed
This is your concern:
class InputSupport
events:
"blur input#myInputText": "_myInputTextBlur"
"focus input#myInputText": "_myInputTextFocus"
_myInputTextBlur = ->
console.error "_myInputTextBlur"
$(".page-header").css "display", "block"
_myInputTextFocus = ->
console.error "_myInputTextFocus"
$(".page-header").css "display", "none"
This will be your BaseView class:
class BaseView extends _(Backbone.View).mixesIn InputSupport
Then in each of you specialized view classes you can extend from BaseView class.
class HeaderView extends BaseView
...
class SidebarView extends BaseView
...
class FooterView extends BaseView
events:
"blur input#myInputText": "_myInputTextBlur"
"focus input#myInputText": "_myInputTextFocus"
"click .someotheButton": 'handleSomeOtherButton'
In the last case you need repeat the events declared in the concern unless you write a more intelligent mixesIn function which merges the two hash... That can be done with _.defaults function easily but in that case you will face a problem with the substraction of events in your descendant classes which will be a smell.
Post a Comment for "Bind Events To All Text Input Fields In All Backbone Views"