I've just started developing an application with javascript for fxos using jQuery Mobile and already got stuck with a framework related problem. For my app I need to use tcp communication provided by mozilla API (mozTCPSocket), it works well when I run it outside from JQM events, but when I do the socket.open() call from a JQM event (eg. pageshow) it looks like the socket object is being killed after each call.
Here is my code:
window.addEventListener('DOMContentLoaded', function() {
'use strict';
var socket;
var host = "someserver";
var port = 6667;
//connect(); // when calling from here, connection works fine
$(document).bind("pageshow", function(e) {
if (typeof e.currentTarget.URL==="string") {
var haystack = $.mobile.path.parseUrl(e.currentTarget.URL);
var needle = /^#server/;
if (haystack.hash.search(needle)!==-1) {
connect(); // ...from here is failing
}
}
});
function connect() {
socket = navigator.mozTCPSocket.open(host,port);
}
socket.ondata = function (event) {
var data = event.data;
var lines = data.split('\r\n');
for (var i=0;i<lines.length;i++) {
if (lines[i].length>0) console.log(lines[i]);
}
}
});
What could be going wrong?
What's certainly wrong here is this:
socket.ondata = function (event) {
var data = event.data;
var lines = data.split('\r\n');
for (var i=0;i<lines.length;i++) {
if (lines[i].length>0) console.log(lines[i]);
}
}
You're setting the ondata
method on an undefined
object. Which means that any call to connect()
later won't have any effect anyway. Also as you're defining a method of an undefined
object, the method above probably is crashing.
You should rewrite your code to something like this.
window.addEventListener('DOMContentLoaded', function() {
'use strict';
var socket;
var host = "someserver";
var port = 6667;
//connect(); // when calling from here, connection works fine
$(document).bind("pageshow", function(e) {
if (typeof e.currentTarget.URL==="string") {
var haystack = $.mobile.path.parseUrl(e.currentTarget.URL);
var needle = /^#server/;
if (haystack.hash.search(needle)!==-1) {
connect(); // ...from here is failing
}
}
});
function connect() {
socket = navigator.mozTCPSocket.open(host, port);
socket.ondata = onData;
}
function onData (event) {
var data = event.data;
var lines = data.split('\r\n');
for (var i=0;i<lines.length;i++) {
if (lines[i].length>0) console.log(lines[i]);
}
}
});