David
David

Reputation: 36404

Coffeescript inline conditionals

I have this piece of coffeescript which is compiling fine, yet it does actually work as it should.

jQuery ($) ->
    eventMethod = window.addEventListener ? "addEventListener" : "attachEvent"
    eventer = window[eventMethod]
    messageEvent = eventMethod == "attachEvent" ? "onmessage" : "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

messageEvent is undefined or false causing an error. Could someone please advise of how to get around this. I'm fairly new to coffeescript, but loving it so far.

Update: upon further inspection it looks to me like coffeescript does not implement the ?/: operators, instead favouring the if/then/else approach.

Upvotes: 1

Views: 558

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146084

You are confusing the existential operator ? with the ternary operator, which in coffeescript is just an if expression.

eventMethod = if window.addEventListener then "addEventListener" else "attachEvent"

Upvotes: 4

Related Questions