Bind events to all text input fields in all Backbone views

两盒软妹~` 提交于 2019-12-25 16:48:26

问题


I am looking for a way to create global bindings that will span all views within the app, so that I do not have to set up these within each view individually.

Bonus points if suggested mechanism has a way for individual input fields or views to opt out from this behaviour.


Details:

I've encountered this error where the virtual keyboard causes a div with positioned: fixed; (the header) to be positioned oddly on the screen, and then be repositioned correctly once more when the keyboard is hidden; I have chosen to solve this using a solution similar to this:

https://stackoverflow.com/a/15537846/194982

Now, it is possible to apply this to all text input elements individually like so:

events: {
    'blur input#myInputText': '_myInputTextBlur',
    'focus input#myInputText': '_myInputTextFocus'
},
_myInputTextBlur: function() { console.error('_myInputTextBlur');
    $('.page-header').css('display', 'block')
},
_myInputTextFocus: function() { console.error('_myInputTextFocus');
    $('.page-header').css('display', 'none')
},

回答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.



来源:https://stackoverflow.com/questions/20111356/bind-events-to-all-text-input-fields-in-all-backbone-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!