Showing posts with label events. Show all posts
Showing posts with label events. Show all posts

Sunday, April 1, 2018

Javascript - get key description for any keyboard layout

1 comment

For a rich web application, I need keyboard shortcuts. Because there are many different keyboard layouts, they have to be configurable. Unfortunately, I can't figure out a way to map keyboard events to human-readable shortcut names such as Ctrl + Alt + Y or Alt + \.

The keypress event is useless since it doesn't fire for all keys. Here are some properties of keydown events:

  • charCode: Works only for printable characters. Deprecated, according to MDN
  • code: Works, but ignores the keyboard layout. When I press Z, I get code: "KeyY" on my German keyboard.
  • key: Works, but gives different results depending on modifiers. E. g. Shift+3 yields key: "§" on my keyboard and key: "#" on most US keyboards.
  • keyCode: The value is not unique. Ä, Ö, Ü or ^ yields keyCode: 0. Deprecated, according to MDN
  • which: Just like keyCode, the value is not unique. Deprecated, according to MDN
  • altKey, ctrlKey, metaKey, shiftKey: Useful for detecting modifier keys

How should I do this? Is it even possible without knowing the user's keyboard layout?

3 Answers

Answers 1

The thing is, at this point in time you can never know the keyboard layout from within the browser, you can only guess and speculate. There are various ways to try some kind of detection, but they are always complex and not out-of-the-box solutions.

However, there are some things which you can do to determine somehow what key has been pressed.

So Keydown will give you (say the event object is e):

e.code: Holds a string that identifies the physical key being pressed. The value is not affected by the current keyboard layout or modifier state, so a particular key will always return the same value. (from mozilla.org)

e.key: The key value of the key represented by the event. If the value has a printed representation, this attribute's value is the same as the char attribute.

e.which and e.keyCode: Although deprecated, will give you the position code of the key on the keyboard and if the e.charCode is 0, then this is either a position code (if < 256) or unicode (that means the keyboard is switched in another language)

Now the tricky part here is that e.key actually represents the unicode character if it is printable and is not from the US keyboard and is not a special key. You can convert this character into decimal number and check the value. If it is a unicode character, it's decimal value will be equal to the which and keyCode values. If it is and ordinary ASCII, it's lowercase value will be equal to the which and keyCode values. Also, before doing this (the conversion), you can check if e.key is a string (like Control, Alt, CapsLock, etc.) or a char (like a, b, c, etc.) So if it is a char, then you convert it.

All this will give you the idea which key has been pressed and what is the native printable character for this key. I don't have a German, Italian or some other keyboard to test, but you get the point.

Oh, and if you worry if Shift+3 yields "§" or "#", you should always represent that combination as Shift+3 no matter the character it yields, not to speak that the same will be produced with the combination of Ctrl+Shift+3. You have to worry only about the alphabetical characters, but I believe I gave you the means to check that.

Also, I believe that you may not need even the e.which and e.keyCode, because the e.key should give you everything.

Answers 2

I think that your problem is not a problem but only an incorrect analyze of the problem and that you have already the answer !

You say that you want to define human readable shortcuts and you refuse key property because when user press Shift+3, key value is § and I think that you are waiting that key value is 3.

The question is "What is human readable ?".

Pressing § and obtaining § or the developper that say it is not normal that when he press § in pressing Shift+3, he obtains § and not Shift+3.

But if user presses § or Shift+3 (on your german keyboard), it is normal that key value is equal to § and you can use keydown event to intercept when user press only 3 or §.

On my french keyboard, I have a key é that is on same key as digit 2. If I press key é (or 2) I obtain 'é' character. If I press key Shift+2 (or Shift+é) I obtain a 2 character.

I can use keydown event to intercept Ctrl+é and Ctrl+2 (=Ctrlt+Shift+2) without problem.

I think that you can use keydown event to intercept §. Intercepting Shift+3 is impossible because shift+3 is equivalent to §.

If your goal is to intercept SHIFT+DIGIT key independently of keyboard layout, you can add some Javascript code to create some exceptions (or filter) for digit keys (but only digit keys), I think that it is not necessary for other keys.

In this case, you can consider keyCode properties to intercept pressing digit keys.

I all situations, trying to know the keyboard's layout is not necessary.

Currently, I work with french/french, french/belgian, french/swiss and american/american keyboard (or Tastatur) and I have encountered same problem in writing a C++ ActiveControl using MFC 20 year ago.

If my answer is not enough good for you, can you post some examples so I can help you for this specific new cases.

Answers 3

You can detect the keyboard input, by combining some of the methods you mentioned. More specifically, you can:

  • Use ctrlKey, altKey, metaKey and shiftKey to detect those specific keys.
  • Combine code and key to detect the physical key that is pressed and the actual value that the key produces (if printable).
  • Utilize code to print special keys such as Enter.

The below example, while far from perfect, shows you where you could start utilizing these methods.

document.addEventListener('keydown', function(e) {    let keyboard = [];    if (e.ctrlKey) keyboard.push('Ctrl');    if (e.altKey) keyboard.push('Alt');    if (e.metaKey) keyboard.push('Meta');    if (e.shiftKey) keyboard.push('Shift');    if (!e.key.includes('Shift') && !e.key.includes('Alt') && !e.key.includes('Meta') && !e.key.includes('Ctrl'))      if (e.code.toLowerCase() === e.key.toLowerCase() || e.code.toLowerCase() === ('Key' + e.key).toLowerCase())        keyboard.push(e.key.toUpperCase())    else keyboard.push(e.code.replace('Key', '').replace('Digit', '').toUpperCase());    let prettyKeyboard = '<p>' + keyboard.map(v => `<kbd>${v}</kbd>`).join(' + ') + '</p>';    document.body.innerHTML += prettyKeyboard;  });

Notes & Considerations

  • The stylization of the keys (capitalized) is up to you, feel free to change it to your liking.
  • Certain keys produce imperfect values, so they have to be mapped using an array in order to be human-readable. Prime examples of this are the backslash and backquote characters.
  • The above example works only for combinations of up to two keys, so you might want to utilize some sort of timeout system along with an array to hold the values of the pressed keys.
  • If you want to make sure you know the user's keyboard layout, show them an on-screen keyboard and ask them to type a specific letter so that you can associate it with a certain layout and go from there. This is what Windows 10 does during installation and it's a pretty good and fool-proof method of keyboard layout detection.
  • Most keyboards have English characters printed on them alongside the keyboard language, so you should consider printing the English key value instead of whatever language the user is using. After all most applications shortcuts are usually shown as English key combinations.
Read More

Sunday, February 26, 2017

React stop other events on that element

Leave a Comment

I have a volume element that shows the volume bar when the user hovers over it. This all works great in desktop. However to get the same functionality on mobile, the user has clicks on the volume element which also toggles the mute click event.

I am wanting to stop that mute event when the user clicks (i.e taps) on that element on mobile.

I don't want to modify the Mute or VolumeBar classes to fix this because these are generic classes in my library that the developer uses.

https://jsfiddle.net/jwm6k66c/2145/

  • Actual: The mute click event gets fired and the volume bar opens.
  • Expected: The mute click event doesn't gets fired and the volume bar opens.

Open the console -> go into mobile view (CTRL + SHIFT + M on chrome) -> click the volume button and observe the console logs.

What I have tried:

Using volumeControlOnClick to stop propogation when the volume bar's height is 0 (i.e not visible), this does not cancel the onClick though.

What I want:

To cancel the mute click event if the user clicks on the volume icon for the first time in mobile. Instead it should only show the volume bar.

const volumeControlOnClick = (e) => {   const volumeBarContainer =     e.currentTarget.nextElementSibling.querySelector('.jp-volume-bar-container');   /* Stop propogation is for mobiles to stop     triggering mute when showing volume bar */   if (volumeBarContainer.clientHeight === 0) {     e.stopPropagation();     console.log("stop propogation")   } };  class Volume extends React.Component {   constructor(props) {     super(props);      this.state = {};   }     render() {     return (         <div className="jp-volume-container">         <Mute onTouchStart={volumeControlOnClick}><i className="fa fa-volume-up" /></Mute>         <div className="jp-volume-controls">           <div className="jp-volume-bar-container">             <VolumeBar />           </div>          </div>        </div>     );   } };  class Mute extends React.Component {     render() {     return (       <button className="jp-mute" onClick={() => console.log("mute toggled")} onTouchStart={this.props.onTouchStart}>         {this.props.children}       </button>     );   } };  class VolumeBar extends React.Component {     render() {     return (         <div className="jp-volume-bar" onClick={() => console.log("bar moved")}>         {this.props.children}       </div>     );   } };  React.render(<Volume />, document.getElementById('container')); 

3 Answers

Answers 1

What you can do is use a flag to indicate you were in a touch event before being in your mouse event, as long as you are using bubble phase. So attach a listener to your container element like this:

let isTouch = false;  const handleContainerClick = () => isTouch = false;  const handleMuteClick = () => {   if (isTouch == false) {     console.log("mute toggled");   } };  const volumeControlOnClick = () => {   isTouch = true; };  class Volume extends React.Component {   constructor(props) {     super(props);      this.state = {};   }    render() {     return (       <div className="jp-volume-container" onClick={handleContainerClick}>         <Mute onTouchStart={volumeControlOnClick} onClick={handleMuteClick}><i className="fa fa-volume-up" /></Mute>         <div className="jp-volume-controls">           <div className="jp-volume-bar-container">             <VolumeBar />           </div>         </div>       </div>     );   } };  class Mute extends React.Component {   render() {     return (       <button className="jp-mute" onTouchStart={this.props.onTouchStart} onClick={this.props.onClick}>         {this.props.children}       </button>     );   } };  class VolumeBar extends React.Component {   render() {     return (       <div className="jp-volume-bar" onClick={() => console.log("bar moved")}>         {this.props.children}       </div>     );   } };  render(<Volume />, document.getElementById('container')); 

If you are not using bubble phase so you can register a timeout of 100ms with the same logic above, where after 100ms you make your flag variable false again. Just add to your touchStart handler:

setTimeout(() => {isTouch = false}, 100); 

EDIT: Even though touch events are supposed to be passive by default in Chrome 56, you call preventDefault() from a touchEnd event to prevent the click handler from firing. So, if you can't modify the click handler of your Mute class in any way, but you can add a touchEnd event, than you could do:

const handleTouchEnd = (e) => e.preventDefault();  const volumeControlOnClick = () => console.log("volumeControlOnClick");  class Volume extends React.Component {   constructor(props) {     super(props);      this.state = {};   }    render() {     return (       <div className="jp-volume-container">         <Mute onTouchStart={volumeControlOnClick} onTouchEnd={handleTouchEnd}><i className="fa fa-volume-up" /></Mute>         <div className="jp-volume-controls">           <div className="jp-volume-bar-container">             <VolumeBar />           </div>         </div>       </div>     );   } };  class Mute extends React.Component {   render() {     return (       <button className="jp-mute" onTouchStart={this.props.onTouchStart} onTouchEnd={this.props.onTouchEnd} onClick={() => console.log("mute toggled")}>         {this.props.children}       </button>     );   } };  class VolumeBar extends React.Component {   render() {     return (       <div className="jp-volume-bar" onClick={() => console.log("bar moved")}>         {this.props.children}       </div>     );   } };  render(<Volume />, document.getElementById('container')); 

Answers 2

Here's what I ended up with. It works because onTouchStart is always calld before onClick if it's a touch event and if not's then the custom logic gets called anyway. It also fires before the hover has happened. This preserves the :hover event. e.preventDefault() did not.

let isVolumeBarVisible;  const onTouchStartMute = e => (   isVolumeBarVisible = e.currentTarget.nextElementSibling     .querySelector('.jp-volume-bar-container').clientHeight > 0 );  const onClickMute = () => () => {   if (isVolumeBarVisible !== false) {     // Do custom mute logic   }   isVolumeBarVisible = undefined; };  <Mute   aria-haspopup onTouchStart={onTouchStartMute}   onClick={onClickMute} >   <i className="fa">{/* Icon set in css*/}</i> </Mute> 

Answers 3

Try this

 render() {         return (       <div className="jp-volume-container" onClick={handleContainerClick}>         <Mute onTouchStart={volumeControlOnClick} onClick={handleMuteClick}><i className="fa fa-volume-up" /></Mute>         <div className="jp-volume-controls">           <div className="jp-volume-bar-container">             <VolumeBar />           </div>         </div>       </div>     );   } };  class Mute extends React.Component {   render() {     return (       <button className="jp-mute" onTouchStart={this.props.onTouchStart} onClick={this.props.onClick}>         {this.props.children}       </button>     );   } };  class VolumeBar extends React.Component {   render() {     return (       <div className="jp-volume-bar" onClick={() => console.log("bar moved")}>         {this.props.children}       </div>     );   } };  render(<Volume />, document.getElementById('container')); 
Read More

Thursday, February 2, 2017

How to get a return value from an engine event handler in PowerShell?

Leave a Comment

I want to use events in PowerShell to separate responsibilities and eliminate dependencies between modules. A child module needs to notify a parent module about its activity and sometimes it needs information in return from the parent module when it raises an event.

This is what I have tried so far. In a real-world scenario I would put the registration-, unregistration and handler function parts in a parent module and the New-Event parts in a child module.

function MyHandler {    param (     [System.Management.Automation.PSEventArgs]$Event   )    Write-Host "In MyHandler now!" -ForegroundColor Yellow    Write-Host "Sender        : $($Event.Sender)"    Write-Host "SourceArgs    : $($Event.SourceArgs)"    Write-Host "MessageData   : $($Event.MessageData)"   Write-Host "TimeGenerated : $($Event.TimeGenerated)"    $Event.MessageData = "This does not make it back."    return "Neither does this." }  # subscribe [String]$MessageData = "Input" Register-EngineEvent -SourceIdentifier Pipo -Action {MyHandler $Event }  # raise event and see what we get back New-Event -Sender "Me" -SourceIdentifier "Pipo" -EventArguments "MyEventArgs" -MessageData $MessageData  # cleanup Unregister-Event -SourceIdentifier Pipo 

This does trigger the call to MyHandler and I can access passed arguments and event properties. The problem is I cannot find a way to get data back from the event handler function to the raiser of the event. My mindset is probably too much C#-oriented, I may be trying to do things in a way that I should go about differently in PS. The whole concept of creating an object and send it down the pipeline in order to raise an event seems odd to me and I do not understand what really happens.

What is the right way to do this?

1 Answers

Answers 1

I found a way that addresses my needs. It turns out I was searching for the wrong keywords, when searching for PowerShell and callbacks I found this question which helped me a lot (particularly Duncan's answer):

Pass a function as a parameter in PowerShell

I worked it into a full example. This is a client script, to be saved as "Client.ps1":

Import-Module -Name ".\Server.psm1" -DisableNameChecking  $script:ClientVar = "Not seen by server, returned by event handler."  function Handle_Initialized {   Write-Host "Handler Initialized is being called."    # a return value is optional   return "=== $script:ClientVar ===" }  function Handle_ProcessedData {    param (     $Argument1,     $Argument2,     $Argument3   )    Write-Host "Handler ProcessedData is called."   Write-Host "Arguments are $argument1, $argument2 and $argument3."    # a return value is optional   return "=== $argument1, $argument2, $argument3 ===" }   Subscribe-Event -Name Initialized  -Handler $function:Handle_Initialized Subscribe-Event -Name ProcessedData -Handler $function:Handle_ProcessedData  Write-Host "" Write-Host "calling with active subscriptions" Write-Host "================================="  Do-ServerStuff  Unsubscribe-Event -Name Initialized Unsubscribe-Event -Name ProcessedData  Write-Host "" Write-Host "calling again with no active subscriptions" Write-Host "================================="  Do-ServerStuff  Remove-Module -Name "Server" 

Then, in the same folder, put this as "Server.psm1":

[ScriptBlock]$script:Handler_Initialized   = $null [ScriptBlock]$script:Handler_ProcessedData = $null  function Subscribe-Event {    param (     [String]$Name,     [ScriptBlock]$Handler   )    switch ($Name) {     Initialized   { $script:Handler_Initialized   = $Handler }     ProcessedData { $script:Handler_ProcessedData = $Handler }   } }  function Unsubscribe-Event {    param (     [String]$Name   )    switch ($Name) {     Initialized   { $script:Handler_Initialized   = $null }     ProcessedData { $script:Handler_ProcessedData = $null }   } }  function Raise-Initialized {    param (   )    if ($script:Handler_Initialized) {     return & $script:Handler_Initialized   } }  function Raise-ProcessedData {    param (     [Object]$Argument1,     [Object]$Argument2,     [Object]$Argument3   )    if ($script:Handler_ProcessedData) {     return & $script:Handler_ProcessedData -Argument1 $Argument1 -Argument2 $Argument2 -Argument3 $Argument3   } }  function Do-ServerStuff {   Write-Host "Before raising event Initialized."   Raise-Initialized   Write-Host "After raising event Initialized."   Write-Host ""   Write-Host "Before raising event ProcessedData."   Raise-ProcessedData -Argument1 "AAA" -Argument2 "BBB" -Argument3 "CCC"   Write-Host "After raising event ProcessedData." } 

And you will find that you have an extensible synchronous event handling system.

Most of the plumbing is in the server module which dictates the prototypes for the handler functions. The client code merely subscribes to and unsubscribes from events and provides the handler implementations. It supports named parameters for all handlers as well as return values (really output values) in the usual PowerShell way. The server knows nothing about any of its clients which I like a lot, dependencies go one way only.

For example, this scheme allows you to build modules that perform pure core logic and nothing else. Rather than logging through some global object you can have the server module raise an event that sends a message and the client can then decide what to do with it and where to send it. This increases the usability of server modules and makes them testable.

It may be a matter of taste, I typically favor using events over dependency injection. With dependency injection the server still needs to know about the type that is injected, with events this is not the case.

Enjoy!

Read More

Saturday, October 1, 2016

Exposing .NET events to COM?

1 comment

I've been trying to expose and fire an event to a VBA client. So far on the VBA client side, the event is exposed and I see the method event handling method added to my module class however the VBA event handling method does not fire. For some reason, when debugging the event is null. Modifying my code with synchronously did not help either.

For the record, I've checked other SO questions but they didn't help.

Any good answers will be appreciated.

[ComVisible(true)] [Guid("56C41646-10CB-4188-979D-23F70E0FFDF5")] [ClassInterface(ClassInterfaceType.None)] [ComSourceInterfaces(typeof(IWebEvents))] [ProgId("MyAssembly.MyClass")] public class MyClass : ServicedComponent, IMyClass {     public string _address { get; private set; }     public string _filename { get; private set; }      [DispId(4)]     public void DownloadFileAsync(string address, string filename)     {         _address = address;         _filename = filename;         System.Net.WebClient wc = new System.Net.WebClient();         Task.Factory.StartNew(() => wc.DownloadFile(_address, _filename))             .ContinueWith((t) =>         {             if (null != this.OnDownloadCompleted)                 OnDownloadCompleted();         });     }     public event OnDownloadCompletedEventHandler OnDownloadCompleted; }  [ComVisible(false)] public delegate void OnDownloadCompletedEventHandler();  [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface IWebEvents {     [DispId(1)]     void OnDownloadCompleted(); } 

This is a good gig for you all bounty hunters, 200 rep points

2 Answers

Answers 1

The key concept in .net code is to define event(s) as method(s) on a separate interface and connect it to the class via [ComSourceInterfacesAttribute]. In the example this is done with this code [ComSourceInterfaces(typeof(IEvents))] where IEvents interface defines the event(s) which should be handled on COM client.

Note to event naming: Event names defined in c# class and interface method names defined on interface must be the same. In this example IEvents::OnDownloadCompleted corresponds with DemoEvents::OnDownloadCompleted.

Then a second interface is defined which represents the public API of the class itself, here it is called IDemoEvents. On this interface methods are defined which are called on COM client.

C# code (builds to COMVisibleEvents.dll)

using System; using System.EnterpriseServices; using System.IO; using System.Net; using System.Runtime.InteropServices; using System.Threading.Tasks;  namespace COMVisibleEvents {     [ComVisible(true)]     [Guid("8403C952-E751-4DE1-BD91-F35DEE19206E")]     [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]     public interface IEvents     {         [DispId(1)]         void OnDownloadCompleted();     }      [ComVisible(true)]     [Guid("2BF7DA6B-DDB3-42A5-BD65-92EE93ABB473")]     [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]     public interface IDemoEvents     {         [DispId(1)]         Task DownloadFileAsync(string address, string filename);     }      [ComVisible(true)]     [Guid("56C41646-10CB-4188-979D-23F70E0FFDF5")]     [ClassInterface(ClassInterfaceType.None)]     [ComSourceInterfaces(typeof(IEvents))]     [ProgId("COMVisibleEvents.DemoEvents")]     public class DemoEvents         : ServicedComponent, IDemoEvents     {         public delegate void OnDownloadCompletedDelegate();         private event OnDownloadCompletedDelegate OnDownloadCompleted;         public string _address { get; private set; }         public string _filename { get; private set; }         private readonly string _downloadToDirectory =              Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);          public async Task DownloadFileAsync(string address, string filename)         {             try             {                 using (WebClient webClient = new WebClient())                 {                     webClient.Credentials = new NetworkCredential(                         "user", "psw", "domain");                     string file = Path.Combine(_downloadToDirectory, filename);                     await webClient.DownloadFileTaskAsync(new Uri(address), file)                         .ContinueWith(t =>                         {                             if (OnDownloadCompleted != null)                             {                                 OnDownloadCompleted();                             }                         }, TaskScheduler.FromCurrentSynchronizationContext());                 }             }             catch (Exception ex)             {                 // Log exception here ...             }         }     } } 

Note to file download: To download the file the method WebClient.DownloadFileTaskAsync is used. It downloads the specified resource to a local file as an asynchronous operation using a task object. Task object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread. Therefore it is necessary to call ContinueWith on main thread because otherwise it won't be possible to execute the OnDownloadCompleted event. Thats why ContinueWith(continuationAction, TaskScheduler.FromCurrentSynchronizationContext) is used.

regasm

C:\Windows\Microsoft.NET\Framework\v4.0.30319>regasm C:\Temp\COMVisibleEvents\bin\Debug\COMVisibleEvents.dll /tlb: C:\Temp\COMVisibleEvents\bin\Debug\COMVisibleEvents.tlb 

VBA client reference to *.tlb file

Add reference to *tlb which was generated by regasm. Here the name of this tlb file is COMVisibleEvents.

enter image description here

Here Excel User Form was used as VBA client. After the button was clicked, the method DownloadFileAsync was executed and when this method completes the event was caught in handler m_eventSource_OnDownloadCompleted. In this example you can download the source codes of the c# project COMVisibleEvents.dll from my dropbox.

VBA client code (MS Excel 2007)

Option Explicit  Private WithEvents m_eventSource As DemoEvents  Private Sub DownloadFileAsyncButton_Click()     m_eventSource.DownloadFileAsync "https://www.dropbox.com/s/0q3dskxopelymac/COMVisibleEvents.zip?dl=0", "COMVisibleEvents.zip" End Sub  Private Sub m_eventSource_OnDownloadCompleted()     MsgBox "Download completed..." End Sub  Private Sub UserForm_Initialize()     Set m_eventSource = New COMVisibleEvents.DemoEvents End Sub 

Result

enter image description here

Answers 2

The fact that your event is null may indicate that you declared your class object on the VBA client side without an WithEvents attribute. In order to receive events, you need to specify the class instance as follows:

Private WithEvents obj As MyAssembly.MyClass 
Read More

Monday, April 25, 2016

Event emitter and automatic registrations of member methods as listeners

Leave a Comment

This is a question with answer, the aim of which is to invite the readers to suggest their own solutions.
I'm quite sure that out there there are more clever approaches than mine, so I'd like to know what those solutions are.
Please, share your knowledge by adding your own answers!!


The goal is to create an emitter class that can be used to dispatch a few events.

An important feature I want to be in the emitter is an easy to use registration facility to attach the listeners to the emitter.

In other terms, I don't want to write functions/methods aimed to attach all the listeners to the emitter, for it could be error prone and I found myself more than once looking for a bug that was due to a missed line of code because of that (a line that would have registered the N-th listener, of course).

Imagine the following structs:

struct E1 { };  struct S {     void receive(const E1 &ev) { /* do something */ } }; 

The registration facility I'm looking for is such a solution for which the following lines of code are enough:

S s; emitter.reg(s); 

And that's all, even if in the future it arises the requirement for one more listener to be added to the struct S, as an example:

struct E1 { }; struct E2 { };  struct S {     void receive(const E1 &ev) { /* do something */ }     void receive(const E2 &ev) { /* do something */ } }; 

How could I write such an emitter?

3 Answers

Answers 1

First the includes:

#include <iostream> #include <vector> #include <type_traits> #include <utility> #include <functional> 

We use the void_t detection helper:

template<class ...> using void_t = void; 

We define a trait for detecting the receive() methods using void_t:

template<class C, class E, class X = void_t<>> struct has_event_handler :       std::false_type {};  template<class C, class E> struct has_event_handler<C, E, void_t< decltype(     std::declval<C>().receive(std::declval<const E>()) ) >> : std::true_type {};  template<class C, class E> constexpr bool has_event_handler_v = has_event_handler<C, E>::value; 

Using this, we can define the emitter class. The variadic arguments are the type of events it can manage:

template<class...> class Emitter;  // Recursive case: template<class E, class... F> class Emitter<E, F...> : Emitter<F...> { public:   // Register:   template<class C>   std::enable_if_t<!has_event_handler_v<C,E>> reg(C& callback) {     Emitter<F...>::reg(callback);   };   template<class C>   std::enable_if_t<has_event_handler_v<C,E>> reg(C& callback) {     handlers_.push_back([&callback](E const& event) { return callback.receive(event); });     Emitter<F...>::reg(callback);   };   void trigger(E const& event)   {     for (auto const& handler : handlers_)       handler(event);       }   template<class G>   void trigger(G const& event)   {     Emitter<F...>::trigger(event);   } private:   std::vector<std::function<void(const E&)>> handlers_; };  // Base case: template<> class Emitter<> { public:   template<class C>   void reg(C& callback) {};   template<class E>   void trigger(E const& event)   {      static_assert(!std::is_same<E,E>::value,        "Does not handle this type of event.");   } }; 

For the trigger() part, another solution would be to use std::enable_if_t<std::is_base_of_v<E, G>>.

And we can use it with:

// Events struct E1 {}; struct E2 {}; struct E3 {};  // Handler struct handler {   void receive(const E1&)   {     std::cerr << "E1\n";   }   void receive(const E2&)   {     std::cerr << "E2\n";   } };  // Check the trait: static_assert(has_event_handler_v<handler, E1>, "E1"); static_assert(has_event_handler_v<handler, E2>, "E2"); static_assert(!has_event_handler_v<handler, E3>, "E3");  int main() {   Emitter<E1, E2> emitter;   handler h;   emitter.reg(h);   emitter.trigger(E1());   emitter.trigger(E2()); } 

Note: I used the _v and _t variants from C++17 in order to have a shorter code but for compatibility with C++11 you might want to use the struct versions (typename std::enable_if<foo>::type, std::is_base_of<B,D>::value, etc.).

Update: it's probably better to use composition instead of inheritance for the recursive case of Emitter:

template<class E, class... F> class Emitter<E, F...> { public:   // Register:   template<class C>   std::enable_if_t<!has_event_handler_v<C,E>> reg(C& callback) {     Emitter<F...>::reg(callback);   };   template<class C>   std::enable_if_t<has_event_handler<C,E>::value> reg(C& callback) {     handlers_.push_back([&callback](E const& event) { return callback.receive(event); });     emitter_.reg(callback);   };   void trigger(E const& event)   {     for (auto const& handler : handlers_)       handler(event);       }   template<class G>   void trigger(G const& event)   {     emitter_.trigger(event);   } private:   std::vector<std::function<void(const E&)>> handlers_;   Emitter<F...> emitter_; }; 

Answers 2

Here it follows a complete example of a possible emitter class that is strongly based on templates and sfinae.
One can compile it using the line g++ -g -std=c++14 main.cpp.
I tried to reduce the code to a minimal example, thus using naked pointers and only a few member methods.

#include <functional> #include <vector> #include <cassert>  template<class E> struct ETag { using type = E; };  template<int N, int M> struct Choice: public Choice<N+1, M> { };  template<int N> struct Choice<N, N> { };  template<int S, class... T> class Base;  template<int S, class E, class... O> class Base<S, E, O...>: public Base<S, O...> {     using OBase = Base<S, O...>;  protected:     using OBase::get;     using OBase::reg;      std::vector<std::function<void(const E &)>>& get(ETag<E>) {         return vec;     }      template<class C>     auto reg(Choice<S-(sizeof...(O)+1), S>, C* ptr)     -> decltype(std::declval<C>().receive(std::declval<E>())) {         using M = void(C::*)(const E &);         M m = &C::receive;         std::function<void(const E &)> fn = std::bind(m, ptr, std::placeholders::_1);         vec.emplace_back(fn);         OBase::reg(Choice<S-sizeof...(O), S>{}, ptr);     }  private:     std::vector<std::function<void(const E &)>> vec; };  template<int S> class Base<S> { protected:     virtual ~Base() { }     void get();     void reg(Choice<S, S>, void*) { } };  template<class... T> class Emitter: public Base<sizeof...(T), T...> {     using EBase = Base<sizeof...(T), T...>;  public:     template<class C>     void reg(C *ptr) {         EBase::reg(Choice<0, sizeof...(T)>{}, ptr);     }      template<class E, class... A>     void emit(A&&... args) {         auto &vec = EBase::get(ETag<E>{});         E e(std::forward<A>(args)...);         for(auto &&fn: vec) fn(e);     } };  struct E1 { }; struct E2 { }; struct E3 { };  struct S {     void receive(const E1 &) { e1 = !e1; }     void reject(const E2 &) { e2 = !e2; }     void receive(const E3 &) { e3 = !e3; }     void check() { assert(e1); assert(e2); assert(e3); }     bool e1{false};     bool e2{true};     bool e3{false}; };  int main() {     S s;     Emitter<E1, E2, E3> emitter;      emitter.reg(&s);     emitter.emit<E1>();     emitter.emit<E2>();     emitter.emit<E3>();     s.check(); }  

Answers 3

My version without inheritance:

template <typename C, typename E> std::false_type has_event_handler_impl(...); template <typename C, typename E> auto has_event_handler_impl(int) -> decltype(static_cast<void>(std::declval<C>().receive(std::declval<const E>())),             std::true_type{});  template <typename C, typename E> using has_event_handler = decltype(has_event_handler_impl<C, E>(0));  template <class... Es> class Emitter { public:      template<class C>     void reg(C& callback) {         const int dummy[] = { 0, (regT<Es>(callback), 0)...};         static_cast<void>(dummy); // Avoid unused variable warning     }      template <typename E>     void emit(const E& event)     {         for (auto const& handler : get_vector<E>()) {             handler(event);         }     }  private:     template <typename E, typename C>     std::enable_if_t<has_event_handler<C, E>::value>     regT(C& callback)     {         auto lambda = [&callback](const E& event) { return callback.receive(event); };         get_vector<E>().push_back(lambda);     }      template <typename E, typename C>     std::enable_if_t<!has_event_handler<C, E>::value>     regT(C&)     {         /* Empty */     }      template <typename E>     std::vector<std::function<void(const E&)>>& get_vector()     {         return std::get<std::vector<std::function<void(const E&)>>>(handlers_);     }  private:     std::tuple<std::vector<std::function<void(const Es&)>>...> handlers_; }; 

Demo

Read More

Saturday, April 2, 2016

Mediate and share data between different modules

Leave a Comment

I am just trying to get my head around event driven JS, so please bear with me. There are different kinds of modules within my app. Some just encapsulate data, others manage a part of the DOM. Some modules depend on others, sometimes one module depends on the state of multiple other modules, but I don't want them to communicate directly or pass one module to the other just for easy access. I tried to create the simplest scenario possible to illustrate my problem (the actual modules are much more complex of course):

I have a dataModule that just exposes some data:

var dataModule = { data: 3 }; 

There is a configModule that exposes modifiers for displaying that data:

var configModule = { factor: 2 }; 

Finally there is a displayModule that combines and renders the data from the two other modules:

var displayModule = {   display: function(data, factor) {     console.log(data * factor);   } }; 

I also have a simple implementation of pub-sub, so I could just mediate between the modules like this:

pubsub.subscribe("init", function() {   displayModule.display(dataModule.data, configModule.factor); }); pubsub.publish("init"); // output: 6 

However this way I seem to end up with a mediator that has to know all of the module-instances explicitly - is there even a way to avoid that? Also I don't know how this would work if there are multiple instances of these modules. What is the best way to avoid global instance-variables? I guess my question is what would be the most flexible way to manage something like that? Am I on the right track, or is this completely wrong? Sorry for not being very precise with my question, I just need someone to push me in the right direction.

2 Answers

Answers 1

You do not need a mediator. Just import data, config, and display and call display(data, config) where you need to.

// import data // import config function render(){     display(data, config) } 

Answers 2

You are on the right track, I'll try to give you that extra push you're talking about:


It you want loose coupling, pub-sub is a good way to go.

But, you don't really need that "mediator", each module should ideally be autonomous and encapsulate its own logic.

This is done in the following way: each module depends on the pubsub service, subscribe to all relevant events and act upon them. Each module also publishes events which might be relevant to others (code samples in a minute, bear with me).

I think the bit you might be missing here is that modules, which use events, will hardly never be just plain models. They will have some logic in them and can also hold a model (which they update when receiving events).

So instead of a dataModule you are more likely to have a dataLoaderModule which will publish the data model (e.g. {data: 3}), once he finishes loading.

Another great requirement you set is sharing data while avoiding global instance-variables - this is a very important concept and also a step in the right direction. What you miss in your solution for this is - Dependency Injection or at least a module system which allows defining dependencies.

You see, having an event driven application doesn't necessarily mean that every piece of the code should communicate using events. An application configuration model or a utility service is definitely something I would inject (when using DI, like in Angular), require (when using AMD/CommonJS) or import (when using ES6 modules).
(i.e. rather then communicating with a utility using events).

In your example it's unclear whether configModule is a static app configuration or some knob I can tweak from the UI. If it's a static app config - I would inject it.

Now, let's see some examples:


Assuming the following:

  • Instead of a dataModule we have a dataLoaderModule
  • configModule is a static configuration model.
  • We are using AMD modules (and not ES6 modules, which I prefer), since I see you stuck to using only ES5 features (I see no classes or consts).

We would have:

data-loader.js (aka dataLoaderModule)

define(['pubsub'], function (pubsub) {     // ... load data using some logic...     // and publish it     pubsub.publish('data-loaded', {data: 3}); }); 

configuration.js (aka configModule)

define([], function () {     return {factor: 2}; }); 

display.js (aka displayModule)

define(['configuration', 'pubsub'], function (configuration, pubsub) {     var displayModule = {         display: function (data, factor) {             console.log(data * factor);         }     };      pubsub.subscribe('data-loaded', function (data) {         displayModule.display(data, configuration.factor);     }); }); 

That's it.

You will notice that we have no global variables here (not even pubsub), instead we are requiring (or injecting) our dependencies.


Here you might be asking: "and what if I meant for my config to change from the UI?", so let's see that too:

In this case, I rather rename configModule to settingsDisplayModule (following your naming convention).

Also, in a more realistic app, UI modules will usually hold a model, so let's do that too.

And lets also call them "views" instead of "displayModules", and we will have:

data-loader.js (aka dataLoaderModule)

define(['pubsub'], function (pubsub) {     // ... load data using some logic...     // and publish it     pubsub.publish('data-loaded', {data: 3}); }); 

settings-view.js (aka settingsDisplayModule, aka config)

define(['pubsub'], function (pubsub) {     var settingsModel = {factor: 2};      var settingsView = {         display: function () {             console.log(settingsModel);              // and when settings (aka config) changes due to user interaction,             // we publish the new settings ...             pubsub.publish('setting-changed', settingsModel);         }     }; }); 

data-view.js (aka displayModule)

define(['pubsub'], function (pubsub) {     var model = {         data: null,         factor: 0     };      var view = {         display: function () {             if (model.data && model.factor) {                 console.log(model.data * model.factor);             } else {                // whatever you do/show when you don't have data             }         }     };      pubsub.subscribe('data-loaded', function (data) {         model.data = data;         view.display();     });      pubsub.subscribe('setting-changed', function (settings) {         model.factor = settings.factor;         view.display();     }); }); 

And that's it.

Hope it helps :)

If not - comment!

Read More