Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable a isInstance method in JavaScript.Cast #86

Open
louispan opened this issue Feb 11, 2017 · 0 comments
Open

Enable a isInstance method in JavaScript.Cast #86

louispan opened this issue Feb 11, 2017 · 0 comments

Comments

@louispan
Copy link
Contributor

Hi, I'm having trouble using Javascript.Cast for more complex types like React's SyntheticEvent

AFAIK there is no prototype exported by React for SyntheticEvent, so my logic for detecting if a javascript value is a SyntheticEvent is e && e.nativeEvent && e.nativeEvent instanceof Event

Unfortunately, this means I cannot use Javascript.Cast since the logic for detecting instance is hard-coded to use js_checkcast, which is:

foreign import javascript unsafe 
  "$1 instanceof $2" js_checkCast :: JSVal -> JSVal -> Bool

Would it be possible to invert the hard-coding and make the Cast class as follows?

class InstanceRef a where
  instanceRef :: a -> JSVal

class Cast a where
  unsafeWrap  :: JSVal -> a
  isInstance :: JSVal -> Maybe a
  default isInstance :: InstanceRef a => JSVal -> Maybe a
  isInstance x = js_checkCast x (instanceRef (undefined :: a))

cast :: forall a. Cast a => JSVal -> Maybe a
cast x | isInstance x = Just (unsafeWrap x)
           | otherwise     = Nothing
{-# INLINE cast #-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant