在Vue JS中侦听对象事件

时间:2018-11-13 10:35:38

标签: javascript vue.js webrtc

我正在使用webrtc,我想执行以下操作:

let connection = new WebSocket('ws://localhost:8080')

connection.onmessage = function (message) { // code }

因此,当我使用connection.send(//message)时,应该触发.onmessage事件。

但是我该如何在vue js中听呢?

这是我的vue代码的一部分:

data: {
    connection: null  
},
created: function() {
    this.connection = new WebSocket('ws://localhost:8080')

    // List cameras and microphones.
    this.listDevices()

    let app = this

    this.connection.onmessage = function (message) { 
       console.log("Got message", message.data)
       let data = JSON.parse(message.data)

       switch(data.type) { 
            case "login": 
                app.onLogin(data.success)
                break
            case "offer": 
                app.onOffer(data.offer, data.name) 
                break
            case "answer": 
                app.onAnswer(data.answer) 
                break
            case "candidate": 
                app.onCandidate(data.candidate) 
                break
            default: 
                break 
        } 
    }

    this.connection.onopen = function() {
        app.send({ 
            type: "login", 
            name: 'myUsername' 
        })
    }
},
methods: {
    send: function(message) {            
        this.connection.send(JSON.stringify(message))
    }
}

如您所见,我尝试使用created的vue方法,但这种方法不起作用。那么,如何监听此.onmessage事件并在其中调用我的vue应用程序中定义的其他方法?

0 个答案:

没有答案