David
David

Reputation: 36454

Coffeescript compiles but does not seem to work

jQuery ($) ->
    eventMethod = if window.addEventListener then "addEventListener" else "attachEvent"
    eventer = window[eventMethod]
    messageEvent = eventMethod == if "attachEvent" then "onmessage" else "message"

    # Listen to message from child window
    eventer messageEvent, (e) ->
        console.log "parent received message!:  #{e.data}"
        newHeight = e.data
        $("#cf-iframe").css("height", newHeight)
    , false

As a follow up to another post. My above coffeescript compiles nicely. Yet it doesn't behave as it should. It doesn't seem to have attached the event listener to the window correctly. Can anyone help me with working out why?

Upvotes: 1

Views: 68

Answers (1)

mu is too short
mu is too short

Reputation: 434965

Niko's right, this doesn't make much sense:

messageEvent = eventMethod == if "attachEvent" then "onmessage" else "message"

The inlined if has higher precedence than == which has higher precedence than = so you're actually saying:

messageEvent = (eventMethod == (if "attachEvent" then "onmessage" else "message"))

The string "attachEvent" is truthy so you're actually saying:

messageEvent = (eventMethod == "onmessage")

or shorter still:

messageEvent = false

The eventer function doesn't know what to do with a boolean so the whole thing ends up doing nothing.

I think you want to say this:

messageEvent = if eventMethod == 'attachEvent' then 'onmessage' else 'message'

Or you could use a single conditional combined with an if expression and a destructured assignment to do it all at once:

[eventer, event] = if window.addEventListener
                       [window.addEventListener, 'message']
                   else
                       [window.attachEvent, 'onmessage' ]
eventer event, ...

This approach keeps everything together and, IMO, results in much clearer code.

Upvotes: 3

Related Questions