How to integrate socket.io with mootools - javascript

I have a question about integration between mootools and socket.io on client :
Suppose :
- server application developed in node.js which have a socket.io listen
I want to define a class to manage connection with the server, client socket.io must reside inside this class.
Actually i'm able to send connection from this class but i'm not able to manage push event. How to correct this code ?
var Push = new Class({
Implements: [Events],
initialize : function() {
this.socketServer = '192.168.1.3';
this.listeningPort = '8080';
this.socketIoUrl = 'http://'.concat(this.socketServer,':', this.listeningPort);
//
this.socketIO = io.connect(this.socketIoUrl, {
'connect timeout' : 500,
'reconnect' : false,
'reconnection delay' : 0,
'reopen delay' : 500,
'max reconnection attempts' : 0
});
// Attach Socket.io events
this.attachEvents();
// Creating a socket.io room
this.socketIO.emit('create', this.filterName);
},
// SOCKET.IO EVENTS
attachEvents : function() {
socketIO.on = function(e) {
log.info('aaa');
socket.on('disconnect', function() {
log.error("SOCKET.IO CLIENT disconnected");
this.fireEvent("disconnect", [ e.data, e ]);
});
socket.on('connect_failed', function() {
log.error("SOCKET.IO connection failed ");
this.fireEvent("connect_failed", [ e.data, e ]);
});
socket.on('message', function() {
log.debug(e.data);
processMessage(e.data);
this.fireEvent("message", [ e.data, e ]);
});
}.bind(this)
return this
}
});

It seems that you've lost this context of your Push class instance.
To fix this problem you'll need to modify the attachEvents function like this:
// SOCKET.IO EVENTS
attachEvents : function() {
var self = this; // save context to variable called "self"
this.socketIO.on('disconnect', function() {
log.error("SOCKET.IO CLIENT disconnected");
self.fireEvent("disconnect", [ e.data, e ]);
});
this.socketIO.on('connect_failed', function() {
log.error("SOCKET.IO connection failed ");
self.fireEvent("connect_failed", [ e.data, e ]);
});
this.socketIO.on('message', function() {
log.debug(e.data);
processMessage(e.data);
self.fireEvent("message", [ e.data, e ]);
});
return this;
}

Now it works.
Socket.io init must be defined in a specific method invoked by initialize. Direct initializatioin in nitialize does not work :
initialize : function(filterName, instrumentCode, fieldList, bankName, userName) {
var self = this;
....
self.initConnection();
self.attachEvents();
},
initConnection : function() {
var self = this;
self.socketIO = io.connect(this.socketIoUrl, {
'connect timeout' : 500,
'reconnect' : true,
'reconnection delay' : 0,
'reopen delay' : 500,
'max reconnection attempts' : 0
});
logger.debug ('socket.io init');
},
attachEvents : function() {
var self = this;
// Attach Socket.io events
//this.attachEvents();
self.socketIO.on('disconnect', function() {
logger.error('Client disconnected');
self.initConnection();
self.resendRequest();
});
self.socketIO.on('connect_failed', function() {
logger.error('Connection failed');
self.initConnection();
self.resendRequest();
});
self.socketIO.on('message', function(data) {
self.processMessage(data);
});
self.socketIO.emit('create', this.filterName);
},
resendRequest : function() {
if (this.operationType == "SUBSCRIBE") {
subscribe();
} else {
unsubscribe();
}
},
Thanks to everyone.

Related

odoo js error Cannot read property 'include' of undefined while include function to base calendar

i want modification the base_calendar.js with new custom function like below
CalendarNotification = require('base_calendar.base_calendar');
console.log("Masuk sini bawah");
CalendarNotification.include({
'click .link2showed': function() {
console.log("ndak yo mlebu kene to");
var action = {
type: 'ir.actions.act_window',
res_model: 'crm.lead',
view_mode: 'form',
view_type: 'form',
views: [[false, 'form']],
res_id: 16644
};
this.do_action(action);
},
});
and this a base_calendar.js odoo addons
var Notification = require('web.notification').Notification;
var CalendarNotification = Notification.extend({
template: "CalendarNotification",
init: function(parent, title, text, eid) {
this._super(parent, title, text, true);
this.eid = eid;
this.events = _.extend(this.events || {}, {
'click .link2event': function() {
var self = this;
this.rpc("/web/action/load", {
action_id: "calendar.action_calendar_event_notify",
}).then(function(r) {
r.res_id = self.eid;
return self.do_action(r);
});
},
'click .link2recall': function() {
this.destroy(true);
},
'click .link2showed2': function() {
this.destroy(true);
this.rpc("/calendar/notify_ack");
},
});
},
});
How do I fix that and what causes it? I've been several times custom function JS like that and it worked well.
Thank in advance for any pointers.

I want the push notification work for registered member

i am trying to register the devuice fror push notification using the phonegap plugin. In the success action of the AJAX i call the registration action but its not alerting the registration ID. can anyone figure out it.
here the index.js
// Begin boilerplate code generated with Cordova project.
var app = {
// Application Constructor
initialize: function () {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function () {
document.addEventListener('deviceready', this.onDeviceReady, false);
connectionStatus = navigator.onLine ? 'online' : 'offline';
if(connectionStatus !="online")
{
//$.mobile.changePage($("#seconddiv"));
window.location.replace("no-internet.html");
}
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function () {
},
setupPush: function() {
console.log('calling push init');
var push = PushNotification.init({
"android": {
"senderID": "xxxxxxxxx"
},
"ios": {
"sound": true,
"vibration": true,
"badge": true
},
"windows": {}
});
console.log('after init');
push.on('registration', function(data) {
console.log('registration event: ' + data.registrationId);
var oldRegId = localStorage.getItem('registrationId');
if (oldRegId !== data.registrationId) {
// Save new registration ID
localStorage.setItem('registrationId', data.registrationId);
// Post registrationId to your app server as the value has changed
}
alert(localStorage.getItem('registrationId'));
var parentElement = document.getElementById('registration');
var listeningElement = parentElement.querySelector('.waiting');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
});
push.on('error', function(e) {
console.log("push error = " + e.message);
});
push.on('notification', function(data) {
console.log('notification event');
navigator.notification.alert(
data.message, // message
null, // callback
data.title, // title
'Ok' // buttonName
);
});
}
};
i call the app.setupPush(); inside the ajax success handler
here the signin.js
var KPSCtuts = KPSCtuts || {};
$("#btn-submit").click(function(){
var userName = $("#txt-username").val();
var password = $("#txt-password").val();
//alert(KPSCtuts.Settings.Url);
$("#loaderIcon").show();
$.ajax({
type: 'POST',
dataType: "json",
url: KPSCtuts.Settings.Url,
data:"username=" + userName + "&password=" + password + "&login=",
success: function (resp) {
if (resp.success === true) {
// Create session.
var today = new Date();
var expirationDate = new Date();
expirationDate.setTime(today.getTime() + KPSCtuts.Settings.sessionTimeoutInMSec);
KPSCtuts.Session.getInstance().set({
userProfileModel: resp.userProfileModel,
userId: resp.userId,
userName: resp.userName,
sessionId: resp.sessionId,
expirationDate: expirationDate,
keepSignedIn:$('#chck-rememberme').is(":checked")
});
app.setupPush();
// Go to main menu.
window.location.replace("index.html");
$("#loaderIcon").hide();
return;
} else {
if (resp.extras.msg) {
$("#ctn-err").html("<p>"+resp.extras.msg+"</p>");
$("#dlg-invalid-credentials").show();
$("#ctn-err").addClass("bi-ctn-err").slideDown();
$("#loaderIcon").hide();
}
}
},
error: function (e) {
//$.mobile.loading("hide");
//console.log(e.message);
// TODO: Use a friendlier error message below.
$("#ctn-err").html("<p>1-Oops! KPSCtuts had a problem and could not log you on. Please try again in a few minutes.</p>");
$("#ctn-err").addClass("bi-ctn-err").slideDown();
$("#loaderIcon").hide();
}
});
});
Try the registration code in onDeviceReady function.Registration ID will be same until you uninstall the app.
In HTML:
<body onload="onLoad()">
In Script:
function onLoad()
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
var push = PushNotification.init({
"android": {
"senderID": "xxxxxxxxx"
},
"ios": {
"sound": true,
"vibration": true,
"badge": true
},
"windows": {}
});
push.on('registration', function(data) {
console.log('registration event: ' + data.registrationId);
});
push.on('error', function(e) {
console.log("push error = " + e.message);
});
push.on('notification', function(data) {
console.log('notification event');
navigator.notification.alert(
data.message, // message
null, // callback
data.title, // title
'Ok' // buttonName
);
});
}

Backbone router.navigate() giving Failed to execute 'pushState' on 'History' error

I'm trying to set up links and routing with Backbone (this is my first Backbone app). In particular, I want a link of the form /restaurants/:id to trigger the show route.
This is my code:
var App = {
Models: {},
Views: {},
Collections: {}
};
// RESTAURANT SCHEMA
// name
// type
// rating (average) - virtual attribute
// points
// ratings
App.Models.Restaurant = Backbone.Model.extend({
urlRoot: '/restaurants',
defaults: {
points: 0,
ratings: 0
},
updateRating: function(points) {
this.set({points: points});
this.set({ratings: this.get('ratings') + 1});
this.rating.set({
rating: this.get('points') / this.get('ratings')
});
this.save(); // PUT /restaurants/:id PUT if model exists, POST if not
}
});
App.Collections.Restaurants = new (Backbone.Collection.extend({
model: App.Models.Restaurant,
url: '/restaurants'
}))();
App.Views.Restaurant = Backbone.View.extend({
template: _.template(
'<div class="page-header"><h1><%= name %></h1></div>' +
'<p>Type: <%= type %></p><br />' +
'<label>Enter rating: </label>' +
'<input type="number" class="form-control" min="1" max="5">'
),
events: {
'change input[type=number]': 'updateRating'
},
updateRating: function() {
var points = this.$el.$(); // TODO
this.model.updateRating(points);
},
render: function() {
var attributes = this.model.toJSON();
this.$el.html(this.template(attributes));
}
});
App.Views.Restaurants = Backbone.View.extend({
template: _.template(
'<div class="page-header"><h1>Restaurants</h1></div>' +
'<ul>' +
'<% App.Collections.Restaurants.forEach(function(restaurant){ %>' +
'<li><%= restaurant.get("name") %></li>' + // using cid's like this doesn't seem right. I think I need to get the id after saving to the database, but I haven't done that yet.
'<% }); %>' +
'</ul>'
),
render: function() {
this.$el.html(this.template());
},
events: {
'click a': function(e) {
e.preventDefault();
App.Router.navigate(e.target.pathname, {trigger: true});
}
}
});
App.Router = Backbone.Router.extend({
routes: {
"restaurants": "index",
"restaurants/:id": "show",
"restaurants/new": "new",
"restaurants/:id/edit": "edit"
},
initialize: function() {
console.log('initialize called');
var PicolaBusala = new App.Models.Restaurant({
name: "Picola Busala",
type: "Italian"
});
var Benihanna = new App.Models.Restaurant({
name: "Benihanna",
type: "Asian"
});
var LemonLeaf = new App.Models.Restaurant({
name: "Lemon Leaf",
type: "Thai"
});
var picolaBusala = new App.Views.Restaurant({model: PicolaBusala});
var benihanna = new App.Views.Restaurant({model: Benihanna});
var lemonLeaf = new App.Views.Restaurant({model: LemonLeaf});
App.Collections.Restaurants.add(PicolaBusala);
App.Collections.Restaurants.add(Benihanna);
App.Collections.Restaurants.add(LemonLeaf);
App.Views.restaurantsView = new App.Views.Restaurants({collection: App.Collections.Restaurants});
App.Views.restaurantsView.render();
$("#app").html(App.Views.restaurantsView.el);
},
start: function() {
console.log('start called');
Backbone.history.start({pushState: true});
},
index: function() {
console.log('index called');
App.Collections.Restaurants.fetch();
$("#app").html(App.Views.restaurantsView.el);
},
show: function(id) {
console.log('show called');
console.log('id: ', id);
},
new: function() {
},
edit: function() {
}
});
$(function() {
App.Router = new App.Router(); // because a) initialize() needs to be called once the DOM loads and b) App.Router needs to be instantiated for .navigate()
App.Router.start();
})
The particular error I get when I click the /restaurants/:id link is Uncaught SecurityError: Failed to execute 'pushState' on 'History': A history state object with URL 'file:///Users/adamzerner/code/getable_challenge/restaurants/c3' cannot be created in a document with origin 'null'.
What am I doing wrong?
The likely problem is that you're not running this on a server. You need to set up a local server using something like MAMP or WAMP or Node for example so you'll end up accessing your page through the browser at a location like localhost:8080. This will allow you to load local content like a JSON file.
If this doesn't solve your problem try taking a look at Javascript history.PushState not working?

Backbone fetch producing 404 error

I have the following backbone model node that I am trying to use to fetch data from the server but at the moment I get a 404 error, I have checked my files and they seem to be correct
var app = app || {};
app.NotesModel = Backbone.Model.extend({
url:'/usernotes',
defaults: {
username:'',
email:'',
about:'',
editorNote:''
}
});
app.NotesView = Backbone.View.extend({
el:'#notes',
events: {
'click #save': 'save'
},
template1: _.template($('#about').html()),
template2: _.template($('#facts').html()),
initialize: function() {
app.NotesModel = new app.NotesModel({});
var email = $('#data-user').text();
app.NotesModel.fetch({data: {email: email},type:'GET' });
this.render();
},
render: function() {
},
This is what the route file looks like
app.get('/account/usernotes/', require('./views/account/usernotes/index').init);
app.get('/account/usernotes/:email', require('./views/account/usernotes/index').find);
and the functions for the routes
'use strict';
exports.init = function(req, res){
if (req.isAuthenticated()) {
//console.log(req.user.email);
res.render('account/usernotes',
{ data : {
user : req.user.email
}
});
}
else {
res.render('signup/index', {
oauthMessage: '',
oauthTwitter: !!req.app.config.oauth.twitter.key,
oauthFacebook: !!req.app.config.oauth.facebook.key,
oauthGoogle: !!req.app.config.oauth.google.key
});
}
};
exports.find = function(req,res) {
console.log('here');
console.log(JSON.stringify(req));
}
Doing the console.log() doesn't give me any output at all.
Here is a similar question.
Try this:
app.NotesModel.fetch({data: $.param({email: email}) });
or this:
app.NotesModel.fetch({data: {email: email}, processData: true });

Backbone collection fetch not firing

I'm new to backbone and I'm trying to send and receive data from the server in Json format. It just won't work. Here's my code (BTW, I'm using backbone aura):
Collection
define(['sandbox', '../models/message'], function(sandbox, Message) {
'use strict';
var Messages = sandbox.mvc.Collection({
model: Message,
url: '/messagelist.php',
localStorage: new sandbox.data.Store('messages-backbone-require'),
parse: function(response){
return response.rows;
}
});
return Messages;
});
Model
define(['sandbox'], function(sandbox) {
'use strict';
var Message = sandbox.mvc.Model({
defaults: {
opened: '',
messageid: '',
phonenumber: '',
numbername: '',
text: ''
},
parse: function(data){
return data;
}
});
return Message;
});
View
define(['sandbox', '../models/message', 'text!../templates/incoming_messages.html'], function(sandbox, Message, incomingMessagesTemplate) {
'use strict';
var AppView = sandbox.mvc.View({
widgetTemplate: sandbox.template.parse(incomingMessagesTemplate),
events: {
'click .refresh': 'refresh'
},
initialize: function() {
this.$el.html(this.widgetTemplate);
sandbox.events.bindAll(this);
this.collection.bind('createMessageList', this.createMessageList);
},
createMessageList: function() {
// Will work with the received data here
},
render: function() {
var handle = 'h4';
this.$el.draggable({handle: handle});
this.createMessageList();
},
refresh: function() {
this.createMessageList();
}
});
return AppView;
});
Main
define(['sandbox', './views/app', './collections/messages'], function(sandbox, AppView, Messages) {
'use strict';
return function(options) {
var messages = new Messages();
new AppView({
el: sandbox.dom.find(options.element),
collection: messages
}).render();
messages.fetch({
data: {
type: 'incoming',
offset: 0,
offsetcount: 25
},
type: 'GET',
success: function() {
console.log(messages.models); // Shows an empty array.
}
});
};
});
I've check logs and it seems that the ajax request (collection.fetch()) is not firing or is not able to communicate with the server. How can I fix this?
The problem is with the Backbone.LocalStorage plugin. When you assign Collection.localStorage, the plugin takes over the fetch command and reads the data from local storage instead of the server.
See my answer in this SO question on some options on how to solve this.

Categories