I think the main value of the addEventListener(name, this) / handleEvent; pattern is that you 1) get the right 'this' in your handler with no extra fuss, and 2) can easily removeEventListener, without messing with bind and needing a reference to the function you added - see this common trap: addEventListener(name, this.onEvent.bind(this)) - try removing that in your destructor! I'm not so worried about separation of concerns here, you can make your handleEvent a dispatcher that hands the event off to a nicely separated thing. Or make a new object with its own handleEvent per-concern.
Personally, I'm not a huge fan of the magic/concat'd method names as they are un-grep-able. But they kinda work once you know where to look I guess. /Sam ----- Original Message ----- From: "[email protected]" <[email protected]> To: "Jonas Sicking" <[email protected]> Cc: "dev-webapi" <[email protected]>, "Alive" <[email protected]>, "dev-b2g" <[email protected]>, [email protected] Sent: Friday, September 26, 2014 3:02:40 PM Subject: Re: mozSettings API refinement proposal I'll speak to the pattern you've mentioned, as it's something I've been wanting to address for a while. I'm not a fan of the multiple `window.addEventListener(name, this)` pattern in their raw state as the `handleEvent` method often becomes a conglomerate of cases. To me this is a violation of separation of concerns and single responsibility principle. On the other hand, having too many `.bind` calls is inefficient as they would each technically generate a duplicate function for handling the invocation of the bound context. Said simpler, using bind creates an additional function, increasing overhead. Although we don't have a unified framework for simplifying this issue, there are patterns and conventions that would make this easier, albeit at the tradeoff of their own smaller overhead, as an example: ```js function Ctor() { Ctor.events.forEach( event => window.addEventListener(event, this['handle_' + event]) ); } Ctor.events = ['a', 'b', 'c']; Ctor.prototype.handle_a = function() {}; Ctor.prototype.handle_b = function() {}; Ctor.prototype.handle_c = function() {}; ``` Obviously this pattern can be modified a number of different ways to suit the preferences of author, but I think something like this is the best solution for having proper separation of concerns and single responsibility, improved readability, as well as having a low overhead. Granted, having access to a standardized Finite State Machine would be much more robust, but that's neither here nor there. :) I'd welcome the opportunity to discuss this further. Thanks, Eli Perelman Software Engineer - Firefox OS _______________________________________________ dev-b2g mailing list [email protected] https://lists.mozilla.org/listinfo/dev-b2g
