mercredi 27 mai 2015

How to manage dynamic event handlers in javascript views?

I am trying to make an application analogous to MS Painter. You have a set of tools, and some interact-able elements on the page.

The elements have a click/drag event handler, but the handlers need to change depending on the tools chosen (e.g. the drag handler for resizing vs drag when using drag tool).

I prefer not to use a series of switch statements inside the elements to check for which tool was selected, as it might be problematic when you change the tool names or something. I thought perhaps a state pattern might come in handy here, but it would make the View object look extremely lengthy.

var Square = new Backbone.View.extend({
    ...
    events: { 
        'drag' : 'onDrag',
        'click': 'onClick',
    },

    onDrag: function (event) {
         if(App.Tool.state == 'resize') this.resizeOnDrag(event)
         else if (App.Tool.state == 'drag') this.dragOnDrag(event)
         ...
    },    

    ...// in some obscure location, 
    ...// a nightmare for maintenance and readability
    resizeOnDrag: function () {
          this.doSomething();
    } 
});

Any suggestions on a better way to handle this?

Aucun commentaire:

Enregistrer un commentaire