This is my code in javascript:
var user = {};
var handlerReference = null;
var myMessages = myApp.messages('.messages', {
autoLayout: true
});
function setListener(name, jid) {
user.name = name;
user.jid = jid;
$("#chatScreenTitle").text(user.name);
handlerReference = connection.addHandler(onMsgReceive, null, 'message', "chat", null, user.jid, {matchBare: true});
}
function onMsgReceive(stanza) {
console.log($(stanza).children("body").text());
myMessages.addMessage({
text: $(stanza).children("body").text(),
type: "received"
}, 'append', true);
}
function sendMessage(message) {
if (message.length == 0) {
myApp.alert("please enter some text", "alert");
}
else {
var uniqueID = connection.getUniqueId("my:code");
var reqChannelsItems = $msg({id: uniqueID, to: user.jid, from: xmpp_user + "#" + XMPP_DOMAIN, type: "chat"}).c("body").t(message);
connection.send(reqChannelsItems.tree());
myMessages.addMessage({
text: message,
type: "sent"
}, 'append', true);
}
}
I can only send and receive one message after that I am not able to send or receive any messsage.
Thanks.
I think you need to use return true at the end of onMsgReceive. If you don't return true it will finish this handler
Related
I am trying to use javascript URLSearchParameters in which a user can type in certain fields to get particular data sets in json file.
The URLSearchParameter seems to work for when you select certain fields but it does not seem to parse the URL correctly in certain situations.
For Example symbol and apikey is a required field.
Optional fields are start date and end date.
When I type in symbol and apikey and leave all of the optional fields empty, the script breaks. When I type any one of the optional fields, it works. My code is provided below. My schema is not like this but below is an example that is similar. I have more optional fields in my final code but if all of them are empty my code continues to break.
Also I would like to know if there is any simpler way to write this code as I'm repeating the code in if else statements and I am repeating the code the same way.
(function() {
// Create the connector object
var myConnector = tableau.makeConnector();
// Define the schema
myConnector.getSchema = function(schemaCallback) {
var cols = [{
id: "symbol",
alias: "symbol",
dataType: tableau.dataTypeEnum.string
}, {
id: "date",
alias: "date",
dataType: tableau.dataTypeEnum.date
}
];
var tableSchema = {
id: "My data",
alias:"My daily data ",
columns: cols
};
schemaCallback([tableSchema]);
};
// Download the data
myConnector.getData = function(table, doneCallback) {
var dataObj = JSON.parse(tableau.connectionData);
const searchParams = new URLSearchParams (dataObj);
const apiCall = `https://mywebsite/getMyData.json?${searchParams}`;
$.getJSON(apiCall, function(resp) {
var feat = resp.results,
tableData = [];
// Iterate over the JSON object
for (var i = 0, len = feat.length; i < len; i++) {
tableData.push({
"symbol": feat[i].symbol,
"date": feat[i].date,
});
}
table.appendRows(tableData);
doneCallback();
});
};
tableau.registerConnector(myConnector);
// Create event listeners for when the user submits the form
$(document).ready(function() {
$("#submitButton").click(function()
{
if ($('#symbol').val().trim().length == 0 || $('#apikey').val().trim().length == 0)
{
$('#errorMsg').show().html("Symbol and APi key can't be blank.");
}
else if ($('#start-date').val().trim().length == 0){
var dataObj = {
apikey: $('#apikey').val().trim(),
symbol: $('#symbol').val().trim(),
endDate: $('#end-date').val().trim(),
}
tableau.connectionData = JSON.stringify(dataObj);
tableau.connectionName = "My Data";
tableau.submit();
}
else if ($('#end-date').val().trim().length == 0){
var dataObj = {
apikey: $('#apikey').val().trim(),
symbol: $('#symbol').val().trim(),
startDate: $('#start-date').val().trim(),
}
tableau.connectionData = JSON.stringify(dataObj);
tableau.connectionName = "My Data";
tableau.submit();
}
else if ($('#start-date').val().trim().length == 0 && $('#end-date').val().trim().length == 0){
var dataObj = {
apikey: $('#apikey').val().trim(),
symbol: $('#symbol').val().trim(),
type: $('#type').val().trim(),
}
tableau.connectionData = JSON.stringify(dataObj);
tableau.connectionName = "My Data";
tableau.submit();
}
else{
var dataObj = {
apikey: $('#apikey').val().trim(),
symbol: $('#symbol').val().trim(),
startDate: $('#start-date').val().trim(),
endDate: $('#end-date').val().trim(),
};
tableau.connectionData = JSON.stringify(dataObj);
tableau.connectionName = "My Data";
tableau.submit();
}
});
});
})();
I am using converse.js to provide chat functionality. I am looking for a way to add reply to specific chat room message. any one know how can i do that?
for example:
in group user1 send: hello
and user2 wants reply to this message and say hello to
my initial code:
<script>
converse.initialize({
authentication: 'login',
//
auto_login: true,
allow_logout: false,
show_client_info: false,
allow_adhoc_commands: false,
allow_contact_requests: false,
hidden_occupants: true,
blacklisted_plugins: [
'converse-register',
'converse-rosterview',
'converse-bookmarks',
'converse-profile',
],
jid: "person#example.com",
password: "somepassword",
auto_join_rooms: [
{
'jid': 'group#conference.example.com',
'nick': 'myname',
'name': 'title',
'minimized': true
},
],
//
auto_reconnect: true,
bosh_service_url: 'https://example.com:7443/http-bind/',
message_archiving: 'always',
view_mode: 'fullscreen'
});
</script>
thanks all.
Finally I find way to solve this problem.
first in convers.js/src/plugins/chatview/view.js add this before onMessageEditButtonClicked:
onMessageReplyButtonClicked (message) {
const currently_correcting = this.model.messages.findWhere('correcting');
const unsent_text = this.el.querySelector('.chat-textarea')?.value;
if (unsent_text && (!currently_correcting || currently_correcting.get('message') !== unsent_text)) {
if (!confirm(__('You have an unsent message which will be lost if you continue. Are you sure?'))) {
return;
}
}
this.insertIntoTextArea(u.prefixMentions(message, true), true, false);
},
and in convers.js/src/components/message-actions.js file add below code before onMessageEditButtonClicked
onMessageReplyButtonClicked(ev) {
ev.preventDefault();
this.chatview.onMessageReplyButtonClicked(this.model);
}
and in convers.js/src/headless/utils/cores.js change the u.prefixMentions function to:
u.prefixMentions = function (message, reply = false) {
/* Given a message object, return its text with # chars
* inserted before the mentioned nicknames.
*/
let text = message.get('message');
(message.get('references') || [])
.sort((a, b) => b.begin - a.begin)
.forEach(ref => {
text = `${text.slice(0, ref.begin)}#${text.slice(ref.begin)}`
});
if (reply){
const lines = text.split('\n');
let newtxt = ""
for(let i = 0;i < lines.length;i++){
if(!lines[i].startsWith(">")){
newtxt += "> " + lines[i] + "\n"
}
}
return "> reply to " + message.get('nick') + ":\n" + newtxt
}
else
return text;
};
Hi I'm having some major issues trying to understand how to datatables to work with server side processing. For some background I'm using a service call Gamesparks to create the backend for a videogame and inside this service they have an implementation of mongodb.
I have an endpoint that fetchs all my users and I can see them in my table but the issue is that I fetch all of them, how can I achieve a pagination?. In the documentation they state that we must put serverSide to true but is not working. I really have no idea on how to proceed I need help.
Gamesparks event to fetch all users
require("LeaderboardMethods");
var playerList = Spark.runtimeCollection("playerList").find({},{"_id":0});
var finalData = [];
while(playerList.hasNext()){
var current = playerList.next();
var playerStats = Spark.runtimeCollection("playerStatistics").findOne({
"playerId":current.playerId
});
var loadedPlayer = Spark.loadPlayer(current.playerId);
var score = getScore(current.playerId);
if(loadedPlayer === null){
var toReturn = {
"playerId": current.playerId,
"displayName": current.displayName,
"email": "DELETED",
"rank": current.rank,
"coins": "DELETED",
"ban": "DELETED",
"score": score
}
finalData.push(toReturn);
} else{
var coins = loadedPlayer.getBalance("COIN");
var toReturn = {
"playerId": current.playerId,
"displayName": current.displayName,
"email": current.email,
"rank":playerStats.rank,
"coins": coins,
"ban": playerStats.isBlocked,
"score":score
}
finalData.push(toReturn);
}
}
Spark.setScriptData("playerList",finalData);
Datatables call
App.getUsers = function(){
var bodyData = {
"#class": ".LogEventRequest",
"eventKey": "GET_PLAYER_DATA",
"playerId": "MY_ID"
}
var table = $('#table1').DataTable({
"dom": "<'row be-datatable-header'<'col-sm-4'l><'col-sm-4'B><'col-sm-4'f>>" +
"<'row be-datatable-body'<'col-sm-12'tr>>" +
"<'row be-datatable-footer'<'col-sm-5'i><'col-sm-7'p>>",
"buttons": [
{
text: 'Edit',
action: function (e, dt, node, config) {
var sel_row = table.rows({
selected: true
}).data();
if (sel_row.length != 0) {
window.location.href = "edit-user.html";
localStorage.setItem("editUser", JSON.stringify(sel_row[0]));
}
}
},
{
text: 'Create',
action: function (e, dt, node, config) {
window.location.href = "create-user.html";
}
},
{
text: 'Delete',
className: 'delete-btn',
action: function (e, dt, node, config) {
var filtered = table.rows({
filter: 'applied',
selected: true
}).data();
// Only open modal when are users selected
if(filtered.length != 0){
$("#proceed-delete").prop('disabled', true)
$("#mod-danger-delete").modal();
if(filtered.length != 1) {
$('#length-users').append(document.createTextNode(filtered.length + " users"));
} else {
$('#length-users').append(document.createTextNode(filtered.length + " user"));
}
$("#delete-confirmation").change(function () {
if ($("#delete-confirmation").val() === "DELETE"){
$("#proceed-delete").prop('disabled', false)
$('#proceed-delete').on('click', function () {
if (filtered.length === 1) {
deleteUserRequest(filtered[0]);
} else {
for (let index = 0; index < filtered.length; index++) {
deleteUserRequest(filtered[index])
}
}
});
}
});
}
}
}, 'selectAll', 'selectNone'
],
"paging":true,
"pageLength":50,
"serverSide":true,
"ajax": {
"data": function (d) {
return JSON.stringify(bodyData);
},
"contentType": "application/json; charset=utf-8",
"url": config.REQUEST_API + '/rs/' + config.API_CREDENTIAL_SERVER + '/' + config.API_SERVER_SECRET + '/LogEventRequest',
"type":"POST",
"dataSrc":function(json){
console.log(json);
$('#loading-row').removeClass('be-loading-active');
return json.scriptData.playerList
},
},
"columns": [
{
data: null,
defaultContent: "<td></td>",
className: 'select-checkbox'
},
{ data: "playerId"},
{ data: "displayName" },
{ data: "email" },
{ data: "score"},
{ data: "rank" },
{ data: "isBlocked" },
{ data: "coins" },
{
"data": null,
"defaultContent": "<button class='btn btn-space btn-primary' onclick='App.click()'>View more</button>"
}
],
"select": {
style: 'multi',
selector: 'td:first-child'
},
}).on('error.dt', function(e, settings, techNote, message){
var err = settings.jqXHR.responseJSON.error;
// GS err
if(err === "UNAUTHORIZED"){
location.href = "pages-login.html";
return true;
} else{
$('#error-container-dt').show();
console.log(message);
return true;
}
});
}
Quick peek into Gamesparks SDK and found this for example:
ListTransactionsRequest
dateFrom Optional date constraint to list transactions from
dateTo Optional date constraint to list transactions to
entryCount The number of items to return in a page (default=50)
include An optional filter that limits the transaction types returned
offset The offset (page number) to start from (default=0)
Now, for paging you need entryCount and offset. First is size of one page, default 50, you can change it. Server returns 'entryCount' no of records.
Offset is the starting record. For example, initial list (1st page) does have 50 records, clicking "Next" button will send request "offset: 51" to the server. And server reply records from 50 (offset) to 100 (offset + entryCount).
var bodyData = {
"#class": ".LogEventRequest",
"eventKey": "GET_PLAYER_DATA",
"playerId": "MY_ID",
"entryCount": entryCount, // you have to send it if you dont like the default value
"offset": offset // gets his value from "NEXT" or "PREV" button
}
Thats how paging works. I'm not able to give more detailed answer as I dont use Gamesparks myself. Hope it gives you least some directon.
I'm a bit confused about the asynchous call to the DataBase.
I just want to have a javasctipt adapter class for the calls to the web sql. But I'm not quite sure how to do this. Propably somebody have a good hint for me.
The function OfflneAppDBAdapter.prototype.IsDeviceConfigured() should return true or false depending if there are any items in the Table DeviceConfig.
function OfflneAppDBAdapter() {
self = this;
this.deviceIsConfigured = false;
this.Init = function () {
$data.Entity.extend("$de.offlineapp.DeviceConfig", {
Id: { type: "int", key: true, computed: true },
Name: { type: "string", required: true },
Token: { type: "string" },
Type: { type: "string" }
});
$data.EntityContext.extend("$de.offlineapp.DataContext", {
DeviceConfig: { type: $data.EntitySet, elementType: $de.offlineapp.DeviceConfig }
});
}
self.Init();
$de.offlineapp.context = new $de.offlineapp.DataContext({
name: "webSql", databaseName: "OfflineApp"
});
$de.offlineapp.context.onReady(function () {
});
}
// ************************************************************************
// PUBLIC METHODS -- ANYONE MAY READ/WRITE
// ************************************************************************
OfflneAppDBAdapter.prototype.AddDeviceConfig = function (deviceName, deviceToken, deviceTyp) {
$de.offlineapp.context.onReady(function () {
var promise = $de.offlineapp.context.DeviceConfig.toArray(function (x) {
if (x.length == 0) {
var emp = new $de.offlineapp.DeviceConfig({ Name: deviceName, Token: deviceToken, Type: deviceTyp });
$de.offlineapp.context.DeviceConfig.add(emp);
$de.offlineapp.context.saveChanges();
}
}
)
});
}
OfflneAppDBAdapter.prototype.IsDeviceConfigured = function () {
$de.offlineapp.context.onReady(function () {
var promise = $de.offlineapp.context.DeviceConfig.toArray(function (x) {
if (x.length == 0) {
this.deviceIsConfigured = true;
}
}
)
});
return this.deviceIsConfigured;
}
var myOfflineAppDBAdapter = new OfflneAppDBAdapter();
myOfflineAppDBAdapter.AddDeviceConfig("DeviceName", "Token", "iPad");
console.log(myOfflineAppDBAdapter.IsDeviceConfigured());
As expected the console prints "false". I' aware that the jaydata call works with callbacks and the callbacks are not part of the main class. But there must be a possibility to do so?
I would really apprechiate any help.
Thank you in advance....
Chris
UPDATE:
As you requested the startup code:
function OfflineApplication()
{
self = this;
}
OfflineApplication.prototype.StartApplication = function () {
//Check if online, then sync and
if (navigator && navigator.onLine === true) {
this.IsDeviceConfigured();
}
else {
}
}
///check if the device has a base configuration
OfflineApplication.prototype.IsDeviceConfigured = function () {
myOfflineAppDBAdapter.GetDeviceConfiguration(function (result) {
if (result.length > 0) {
myOfflineAppDBAdapter.deviceIsConfigured = true;
myOfflineApplication.HasDeviceAnApplication();
}
else {
///Get the device base conf from the server.
myOfflineAppSynchronisationAdapter.getDeviceConfigurationByToken(token, myOfflineApplication.HasDeviceAnApplication);
myOfflineAppDBAdapter.deviceIsConfigured = true;
}
});
}
///check if the device has an "application config" in general
OfflineApplication.prototype.HasDeviceAnApplication = function () {
myOfflineAppDBAdapter.GetDeviceAnApplication(function (result) {
if (result.length > 0) {
myOfflineApplication.IsDeviceApplicationVersionLatest(result);
}
else {
myOfflineApplication.GetApplication(false);
}
});
}
///the application config could differ from time to time, so we have to check if a different application should be synct with the device
OfflineApplication.prototype.IsDeviceApplicationVersionLatest = function (result) {
myOfflineAppDBAdapter.DeleteDeviceAnApplication(function () { });
console.log(result);
}
///get the application from the server
OfflineApplication.prototype.GetApplication = function (clearConfig) {
if (clearConfig === true)
{
}
myOfflineAppSynchronisationAdapter.getDeviceApplicationByToken(token, myOfflineApplication.LoadApplication);
}
OfflineApplication.prototype.LoadApplication = function () {
console.log('Now everything is finde and the application gets loaded..');
}
var myOfflineAppDBAdapter = new OfflneAppDBAdapter();
var myOfflineAppSynchronisationAdapter = new OfflineAppSynchronisationAdapter();
var myOfflineApplication = new OfflineApplication();
myOfflineApplication.StartApplication();
There is no sync way. You handling promises wrong. Make your code simple :) You'll need something like this:
$data.Entity.extend("$de.offlineapp.DeviceConfig", {
Id: { type: "int", key: true, computed: true },
Name: { type: "string", required: true },
Token: { type: "string" },
Type: { type: "string" }
});
$data.EntityContext.extend("$de.offlineapp.DataContext", {
DeviceConfig: { type: $data.EntitySet, elementType: $de.offlineapp.DeviceConfig }
});
var context = new $de.offlineapp.DataContext({
name: "webSql", databaseName: "OfflineApp"
});
function AddDeviceConfig(deviceName, deviceToken, deviceTyp) {
return context.DeviceConfig.toArray()
.then(function (x) {
if (x.length == 0) {
var emp = new $de.offlineapp.DeviceConfig({ Name: deviceName, Token: deviceToken, Type: deviceTyp });
context.DeviceConfig.add(emp);
return context.saveChanges();
}
})
}
function IsDeviceConfigured() {
return context.DeviceConfig.toArray()
.then(function (x) {
return x.length > 0;
})
}
context.onReady()
.then(IsDeviceConfigured)
.then(console.log)
.then(function() { return AddDeviceConfig("DeviceName", "Token", "iPad"); })
.then(IsDeviceConfigured)
.then(console.log);
here's a fiddle which does this: http://jsfiddle.net/JayData/cpT5q/1/
Im new to YUI3; Im trying to poll a datasource every 10 seconds to refresh a datatable. But with the code below it says there is 'No Data To Display'... Sorry for the large amount of code...
YUI().use("datatable", "datasource-get", "datasource-jsonschema", "datatable-datasource", "datasource-polling", "datasource-function", function (Y) {
var url = "http://query.yahooapis.com/v1/public/yql?format=json" +
"&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
query = "&q=" + encodeURIComponent(
'select * from local.search ' +
'where zip = "94089" and query = "pizza"'),
dataSource,
table;
dataSource = new Y.DataSource.Get({ source: url });
dataSource.plug(Y.Plugin.DataSourceJSONSchema, {
schema: {
resultListLocator: "query.results.Result",
resultFields: [
"Title",
"Phone",
{
key: "Rating",
locator: "Rating.AverageRating",
parser: function (val) {
// YQL is returning "NaN" for unrated restaurants
return isNaN(val) ? -1 : +val;
}
}
]
}
});
intervalId = dataSource.setInterval(10000, {
request : query,
callback: {
success: function (e) {
table.datasource.load(e.response);
},
failure: function (e) {
}
}
});
table = new Y.DataTable({
columns: [
"Title",
"Phone",
{
key: "Rating",
formatter: function (o) {
if (o.value === -1) {
o.value = '(none)';
}
}
}
],
summary: "Pizza places near 98089",
caption: "Table with JSON data from YQL"
});
table.plug(Y.Plugin.DataTableDataSource, { datasource: dataSource });
// This line works (but it doesnt poll)
//table.datasource.load({ request: query });
table.render("#pizza");
});
The line I am not sure about is...
success: function (e) {
table.datasource.load(e.response);
},
The following should fit your needs: http://developer.yahoo.com/yui/examples/datatable/dt_polling.html