在 Scala js 中使用氛围

Using atmosphere with Scala js

如何使用 Scala JS 访问气氛 API?

假设我在 javascript 中有以下内容:

var socket = $.atmosphere
...
var request = {
    url: "myurl/path",
    ...
};

request.onOpen = function(response) {
    ...
    subSocket.push("init")
};
...
socket.subscribe(request);

它在 Scala JS 中的等价物是什么?

我想出了以下解决方案:

@JSName("$.atmosphere")
object Atmosphere extends js.Object {

    def info(msg: String): Unit = js.native
    def subscribe(request: js.Object): Unit = js.native
}

trait Response extends js.Object {
    val status: Int = js.native
    val reasonPhrase: String = js.native
    val responseBody: String = js.native
    val headers: Array[String] = js.native
    val state: String = js.native
    val transport: String = js.native
    val error: String = js.native
    val request: String = js.native
    val partialMessage: String = js.native
    val errorHandled: Boolean = js.native
    val id: Int = js.native
}

class Request(url: String) {

    def contentType = "application/json"
    def logLevel = "debug"
    def transport = "transport"
    def fallbackTransport = "long-polling"

    def onOpen(res: Response) = {}
    def onReconnect(req: Request, res: Response) = {}
    def onMessage(res: Response) = {}
    def onClose(res: Response) = {}
    def onError(res: Response) = {}

    def literal = js.Dynamic.literal(
        url = url,
        contentType = contentType,
        logLevel = logLevel,
        transport= transport,
        fallbackTransport = fallbackTransport,
        onOpen = { (res: Response) => onOpen(res) },
        onReconnect = { (req: Request, res: Response) => onReconnect(req, res) },
        onMessage = { (res: Response) => onMessage(res) },
        onClose = { (res: Response) => onClose(res) },
        onError = { (res: Response) => onError(res) }
    )
}

用法是:

val request = new Request("myurl/path") {
    override def onOpen(res: Response) = {
        g.console.log("Opened " + res.responseBody)
    }
}
Atmosphere.subscribe(request.literal)

这样我就可以覆盖请求的各种 properties/handlers。我想知道这是否可以改进。例如,是否有替代 JSName 用法的方法?

@JSName("$.atmosphere")