Reputation: 101
I have a web app up and running. It is for a gaming platform, where 1 to 5 player(s) click something, data gets sent to the server and the server sends back data to all the clients. The clients then update their DOM through jQuery.
Now I am developing a mobile app for this platform. The web app uses HTML5, CSS3 and jQuery on the client side, cakePHP and Ratchet for websockets on the server side. For the mobile app, I am using Ionic.
Since I do not want to rewrite all the code of the websocket for node.js, I am not using socket.io on the client side. Rather, I leave the server side websocket code and use the jQuery code from the client of the web app. In Ionic, I pasted it into the ngAfterViewInit() function. Everything works, except I would like to be able to pass variables. For example:
ngAfterViewInit()
$(document).ready(function(){
var host = "quiztime.live"; var port = 8010;
var socket = 'wss://' + host + '/wss' + port + '/' + port;
var conn = new WebSocket(socket);
conn.onopen = function(e) {
var PLAY = 7;
var msg = { 'type':PLAY, 'user_id': this.user_id, 'game_id': this.game_id };
conn.send(JSON.stringify(msg));
}
});
which gives an error because this.user_id and this.game_id are of course not defined, for in the context of conn.onopen() "this" now refers to the websocket, not to the Ionic class.
How can I use variables from my Ionic class within jQuery in the ngAfterViewInit() function?
Or is there a better way altogether to implement this project in Ionic?
Upvotes: 0
Views: 969
Reputation: 36
I question the use of jQuery in this case, but you probably want to use ES6 notation to be able to get to the highest this
reference:
ngAfterViewInit() {
$(document).ready(() => {
var host = "quiztime.live"; var port = 8010;
var socket = 'wss://' + host + '/wss' + port + '/' + port;
var conn = new WebSocket(socket);
conn.onopen = (e) => {
var PLAY = 7;
var msg = { 'type':PLAY, 'user_id': this.user_id, 'game_id': this.game_id };
conn.send(JSON.stringify(msg));
}
});
}
Upvotes: 1