how to access javascript function - javascript

I have this code for websocket. I want to call function broadcast for lRes. how can I do this?
var lRes = jwsc.logon('ws://localhost/WS', 'sendToWS', 'root', {
// OnOpen callback
OnOpen: function(aEvent) {
},
// broadcast callback
broadcast: function() {
var lRes = jwsc.broadcastText(
"",
lMsg // broadcast this message
);
},
// OnMessage callback
OnMessage: function(aEvent, aToken) {
},
// OnClose callback
OnClose: function(aEvent) {
},
});

Well, Here I suggest you to call your function like :-
lRes.broadcast();

Related

Get access to closure dojo object when callback scope was entered

I have a dojo object, I want to do a retry connection to a web socket. However, the connection to the web socket is triggered by a callback function. I tried subscribing to a topic to allow reconnect without using this. However, if the class has two or more instance, it gets all the subscribed message on all instance of MyClass. Is there a way to only let the original instance that fail to connect to get the subscribed message?
// Dojo class
dojo.declare("MyClass", null, {
constructor: function() {
dojo.subscribe("WebSocketConnect", this, function() {
this.DoConnect();
});
},
DoConnect: function() {
this.myWebSocket = new WebSocket('ws://192.0.0.1');
// ウェブソケットは閉じたイベント
this.myWebSocket.onclose = function () {
// The this in this clousure is "myWebSocket"
setTimeout(function() {
dojo.publish("WebSocketConnect", [ ] );
}, 5000);
};
}
}
Note: The project I am working on uses dojo 1.4. Quite old but I have no permission to upgrade it.
Any particular reason you dont want to connect to this?
When you publish or subscribe, it is dependent on the string id used to identify the "event", If you could make it unique for each instance then you could prevent the function execute on all instance.
// Dojo class
dojo.declare("MyClass", null, {
uniqueID:"",
constructor: function() {
this.uniqueID = <generate unique id>;
dojo.subscribe("WebSocketConnect" + this.uniqueID, this, function() {
this.DoConnect();
});
},
DoConnect: function() {
var self = this;
this.myWebSocket = new WebSocket('ws://192.0.0.1');
// ウェブソケットは閉じたイベント
this.myWebSocket.onclose = function () {
// The this in this clousure is "myWebSocket"
setTimeout(function() {
dojo.publish("WebSocketConnect" + self.uniqueID, [ ] );
}, 5000);
};
}
}
How you generate the uniqueID is upto you, it could be as simple as a global counter or use some logic to create a GUID. Anything will work as long as it is unique.
Use a dynamic topic name:
// Dojo class
define(['dijit/registry', 'dojo/_base/declare', 'dojo/topic'], function(registry, declare, topic) {
declare("MyClass", null, {
constructor: function() {
var uniqId = registry.getUniqueId('WebSocketConnect'),
doConnect = this._DoConnect;
//for external use
this.DoConnect = function() {
doConnect(uniqId);
}
//from internal fail
topic.subscribe("WebSocketConnect" + uniqId, this.DoConnect());
},
_DoConnect: function(uniqId) {
this.myWebSocket = new WebSocket('ws://192.0.0.1');
// ウェブソケットは閉じたイベント
this.myWebSocket.onclose = function() {
// The this in this clousure is "myWebSocket"
setTimeout(function() {
topic.publish("WebSocketConnect" + uniqId, []);
}, 5000);
};
}
}
});
});
but best is to use hitch:
// Dojo class
define(['dojo/_base/declare'], function(declare) {
declare("MyClass", null, {
DoConnect: function() {
this.myWebSocket = new WebSocket('ws://192.0.0.1');
// ウェブソケットは閉じたイベント
this.myWebSocket.onclose = lang.hitch(this, function() {
setTimeout(lang.hitch(this, 'DoConnect'), 5000);
});
}
}
});
});

Pubnub javascript is not receiving callbacks or message for some reason

Just want to understand why my pubnub javascript code does not receive a message from a channel. I can subscribe and publish, but if another browser sends a new publish message, the other browser can not receive the message. heres my code:
$(document).ready(function () {
var pubnub = PUBNUB.init({
subscribe_key: 'subscribe-key-here',
publish_key: 'publish-key-here'
});
pubnub.subscribe({
channel : "my-channel",
message : function(m){ console.log(m) },
callback : function (message) { console.log("callback: ", message)},
connect : function() {
console.log("Connected")
pubnub.publish({
channel: 'my_channel',
message: { "color" : "blue" },
callback : function(details) {
console.log(details)
}
});
},
disconnect : function() { console.log("Disconnected") },
reconnect : function() { console.log("Reconnected") },
error : function() { console.log("Network Error") },
restore : true
})
});
by the way this code is running/testing on my nodejs localhost server and in chrome and firefox browser.
Code Bug - You have a typo in your channel name:
subscribe uses my_channel
publish uses my-channel
Also, you are using two parameters that mean the same thing in the subscribe: message is an alias for callback
And for your publish, success is an alias (in JavaScript/Node v3.7.20+) for callback and it recommended (just because it makes more sense).
I have removed the callback parameter from your subscribe and replace callback with success in your code below.
Corrected code:
$(document).ready(function () {
var pubnub = PUBNUB.init({
subscribe_key: 'subscribe-key-here',
publish_key: 'publish-key-here'
});
pubnub.subscribe({
channel : "my_channel",
message : function (message) { console.log("callback: ", message)},
connect : function() {
console.log("Connected")
pubnub.publish({
channel: 'my_channel',
message: { "color" : "blue" },
success : function(details) {
console.log(details)
}
});
},
disconnect : function() { console.log("Disconnected") },
reconnect : function() { console.log("Reconnected") },
error : function() { console.log("Network Error") },
restore : true
})
});

Test binding of a custom event to a callback function with Backbone and Jasmine

I'm trying to test to make sure a custom event was bound to upon showing of a dialog. Here is my code:
setupListener = function () {
appEvent.on('some_event', theHandler);
};
theHandler = function (responseData) {
....
};
this.show = function () {
setupListener();
};
Note: setupListener is a private function. Here's my test code that works:
it('appEvent.on was called', function () {
spyOn(appEvent, 'on');
dialogView.show();
var theHandler = function (responseData) {
....
};
expect(appEvent.on).toHaveBeenCalled('some_event', theHandler);
});
But now I want to check the "on" function was called with correct parameters:
it('appEvent.on was called with right parameters', function () {
spyOn(appEvent, 'on');
dialogView.show();
var theHandler = function (responseData) {
....
};
expect(appEvent.on).toHaveBeenCalledWith('some_event', theHandler);
});
But I get the error:
Expected spy on to have been called with [ 'some_event', Function ] but actual calls were [ 'some_event', Function ]
The problem looks to be with the handler. How do I check the "on" function was called with the handler?
You should wrap the handler function like:
expect(appEvent.on).toHaveBeenCalledWith('some_event', jasmine.any(theHandler));

renderAll function does not invoke

Scenario
I am making app using backbonejs, requirejs and jquery. I am retrieving data from remote server. Once the data is fetched, then I want to display it to the user.
Problem
First I fetch data inside app.js file then I make a instance of MoviesView and pass collection in to this view. Inside MoviesView, I have initialize function and inside this function I am listening to an Event triggered by router. Once that event is listened then it should call renderAll function. The problem lies here, it does not invoke renderAll function at all.
My code
here is function where I am fetching data from the server
fetchBoxOfficeMovies: function () {
var movieCollection = new MoviesCollection;
movieCollection.fetch({success: this.successCallback, error: this.errorCallback}).then(function () {
//console.log(movieCollection.toJSON());
new MoviesView({ collection: movieCollection });
});
},
successCallback: function () {
console.log('successCallback');
},
Here is the router where I am triggering an event
routes: {
'': 'index'
},
index: function () {
App.Vent.trigger('init');
console.log('router');
}
And here is initialize and renderAll functions inside MoviesView
initialize: function () {
App.Vent.on('init', this.renderAll, this);
console.log('movies view');
},
renderAll: function () {
console.log('renderAll');
},
Output which I see in my console
Here is what I see in my console
router
successCallback
movies view
As you can see I do not see renderAll in my console.
Question
Why don't I see renderAll and how can I fix this?
UPDATE
Here is my entire App view
var App = Backbone.View.extend({
el: 'body',
initialize: function () {
App.router = new MainRouter();
Backbone.history.start();
this.fetchBoxOfficeMovies();
},
fetchBoxOfficeMovies: function () {
var movieCollection = new MoviesCollection;
movieCollection.fetch({success: this.successCallback, error: this.errorCallback}).then(function () {
//console.log(movieCollection.toJSON());
new MoviesView({ collection: movieCollection });
});
},
successCallback: function () {
console.log('successCallback');
},
errorCallback: function () {
console.log('errorCallback');
}
});
As it can be seen that I am making new instance of MainRouter before calling fetchBoxOfficeMovies, which means I am triggering event before everything else.
As DCoder said, you got the order wrong. Rename your console.log to understand better what's happening.
router -> I trigger a 'init' event
successCallback -> successCallback
movies view -> I start listening 'init' events NOW
Suggested 'Fix':
movieCollection.fetch({
success: this.successCallback,
error: this.errorCallback
}).then(function () {
//console.log(movieCollection.toJSON());
var moviesView = new MoviesView({ collection: movieCollection });
moviesView.renderAll()
});

Phonegap in Android onDeviceReady function

I am using phonegap in android development. I wrote that PoC, however I can not figure out why it does not change the latitude of profile variable. Actually
alert(profile.latitude);
runs before the
geoCode.setLocation();
here is my code;
document.addEventListener("deviceready", onDeviceReady, false);
var profile = {
name: "",
id: "red",
latitude: "xx",
longtitude: "",
setCoordinates: function (latit, longt) {
this.latitude = latit;
this.longtitude = longt;
}
};
var geoCode = {
onSuccess: function (position) {
profile.latitude = position.coords.latitude;
},
onError: function (error) {
},
setLocation : function () {
navigator.geolocation.getCurrentPosition(this.onSuccess, this.onError);
}
};
// Wait for PhoneGap to load
//
function onDeviceReady() {
geoCode.setLocation();
//alert("2");
alert(profile.latitude);
};
thanks in advance
navigator.geolocation.getCurrentPosition is an asynchronous function. You need to do something like :
var geoCode = {
setLocation : function (callback) {
onSuccess: function (position) {
callback(position.coords.latitude);
},
onError: function (error) {
},
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
};
// Wait for PhoneGap to load
//
function onDeviceReady() {
geoCode.setLocation(function(latitude) {
alert(latitude);
});
};
Quite simply it is because the call to navigator.geolocation.getCurrentPosition() is an asynchronous call. Thereby the execution of the program continues and you see the alert. Sometime after the alert is show the onSuccess call of your geoCode class is called updating the profile.latitude value.

Categories

Resources