How to html function store in database - database

// -------------------------------------------------------
// Called when the spin animation has finished by the callback feature of the wheel because I specified callback in the
parameters.
// -------------------------------------------------------
function alertPrize()
{
// Get the segment indicated by the pointer on the wheel background which is at 0 degrees.
var winningSegment = theWheel.getIndicatedSegment();
// Just alert to the user what happened.
// In a real project probably want to do something more interesting than this with the result.
if (winningSegment.text == 'LOOSE TURN')
{
var audio = new Audio('clickUp.mp3');
audio.play();
alert('Sorry but you loose a turn.');
}
else if (winningSegment.text == 'BANKRUPT')
{
var audio = new Audio('clickUp.mp3');
audio.play();
alert('Oh no, you have gone BANKRUPT!'); ***<----- Data out put want to database***
}
else
{
var audio = new Audio('click.mp3');
audio.play();
alert("You have won " + winningSegment.text); ***<----- Data out put want to database***
}
}
Data output I want to store it to database
Thank you advance.

Related

cancel process without using delay task

I have the following delay task in the below method:
exportDataToCSV: function () {
var me = this,
grid = this.option.up('grid');
var mask = Ext.widget('processingmessagebox', {
target: grid,
progressMessage: 'exporting',
isProcessing: true,
targetFunctions: {
ConfirmCancelClick: me.stopExportingData
}
});
mask.getViewModel().set({ ShowCancelBox: 'block' });
var grdStore = grid.getStore();
var grdProxy = grdStore.getProxy();
exportData = new Ext.util.DelayedTask(function () {
me.printDataToCSV(grid, mask);
});
exportData.delay(2000);
},
stopExportingData: function () {
exportData.cancel();
}
This is working fine. But, I am trying to cancel the "exportdata" process without using delay task. Any suggestions on this?
You kind of can't. Javascript - and thus ExtJS - is single-threaded. If your code is busy doing something, it can't respond to a cancel button.
In order to make a long-running task cancelable - or even just to allow a progress bar to update - it needs to be broken up into a series of steps. These steps need to then be put on the task queue - something that ExtJS's delayed task does for you.
For something like export data to a CSV, a common approach would be to create a task that exports, say, a dozen records, and then puts another task to read the next dozen.
There are certainly other approaches than using DelayedTask in particular, but they all revolve around the underlying setTimeout or setInterval methods.
Here's an example using a regular ExtJS task, and not DelayedTask:
var readNextDozenRecords = function(indexToReadFrom) { ... }
var writeDataChunk = function(recordsToWrite) { ... }
var taskConfig = {
currentIndex: 0,
interval: 10, // runs every 10ms or so.
run: function() {
var nextDataChunk = readNextDozenRecords(currentIndex);
if (nextDataChunk.length == 0) {
this.stop(); // 'this' scope is the running task.
return;
}
currentIndex += nextDataChunk.length;
writeDatakChunk(nextDataChunk);
}
}
exportData = Ext.TaskManager.newTask(taskConfig);
// The exportData can be manually canceled by calling the `stop` method.

WPF - Set Window Owner

I have the following case:
A window is shown the the reference to that is stored in a utility class.
Later a modal dialog needs to appear above that window; so I am doing the following:
OptionalMessageBox message = new OptionalMessageBox(title, errorMessage.ToString(), MessageImage.Warning);
if (UIUtilities.TopWindow != null)
{
UIUtilities.TopWindow.Dispatcher.Invoke(() => message.Owner = UIUtilities.TopWindow);
UIUtilities.TopWindow.Dispatcher.Invoke(() => message.ShowDialog());
}
else
{
message.ShowDialog();
}
However this is give the classic 'The calling thread cannot access this object because a different thread owns it' though I don't understand why as I am using the dispatcher for the TopWindow variable. As a note (and out of desperation) I tried putting the calls on the message variable I just created - that didn't work either but I didn't expect that to be the problem as how can I now own it if I have just made it!
Any advice would be greatly appreciated.
Try this:
if (UIUtilities.TopWindow != null)
{
UIUtilities.TopWindow.Dispatcher.Invoke(() =>
{
var message = new OptionalMessageBox(title, errorMessage.ToString(), MessageImage.Warning);
message.Owner = UIUtilities.TopWindow;
message.ShowDialog();
});
}
else
{
var message = new OptionalMessageBox(title, errorMessage.ToString(), MessageImage.Warning);
message.ShowDialog();
}
You can use this
App.Current.Dispatcher.Invoke(() => {
OptionalMessageBox message = new OptionalMessageBox(title, errorMessage.ToString(), MessageImage.Warning);
message.Owner = App.Current.MainWindow;
message.ShowDialog();
});

coordinating geoFire Ready and key_entered events

I am new to GeoFire, FireBase and Angular. I am trying to create a function that will take some coordinates and return some objects in vicinity of those coordinates.
I return a promise from the function which I assign to a scope variable used in the view hoping that when the promise is resolved by the ready event the array of objects in vicinity will be available.
obj.findGroupsInViscinity = function(pos){
var gFire = factoryAuth.geoFire;
var fbaseRef = factoryAuth.usersRef;
var groupsInQuery = {};
var groupsInQueryAr = [];
var deferred = $q.defer();
var geoQuery = gFire.query({
center: [pos.coords.latitude, pos.coords.longitude],
radius: 2
})
geoQuery.on("key_entered", function(groupId, groupLocation, distance) {
console.log("--> key_entered 1");
groupsInQuery[groupId] = true;
// Look up the vehicle's data in the Transit Open Data Set
fbaseRef.child("groups").child(groupId).once("value", function(dataSnapshot) {
console.log("--> key_entered 2");
// Get the vehicle data from the Open Data Set
group = dataSnapshot.val();
// If the vehicle has not already exited this query in the time it took to look up its data in the Open Data
// Set, add it to the map
if (group !== null && groupsInQuery[groupId] === true) {
console.log("Adding group", group);
// Add the group to the list of groups in the query
groupsInQuery[groupId] = group;
groupsInQueryAr.push({"name": group.name});
}
})
}) // end ke_entered monitoring
geoQuery.on("ready", function() {
console.log("GeoQuery ready event received. groupsInQueryAr = ", groupsInQueryAr);
deferred.resolve(groupsInQueryAr);
geoQuery.cancel();
console.log("GeoQuery canceled");
}) // Cacnel the geoQuery once we have gotten all the groups in viscinity
return deferred.promise; // Return a promise that will be resolved when ready event fires
}
Included below the console output from calling this function.
What I notice is that the key_entered part of the code is called twice in succession but before the code to process the key_entered event completes, the ready event is called because all key_entered events have fired. So while the key_entered part of the logic is building out the array I want to pass in resolving the promise, it is not ready at the time I resolve the promise in the ready event.
How can I ensure that I resolve the promise after all key_entered events have been processed and my array of objects has been built out properly?
Thanks,
Sanjay.
I would say that this is a bit of an XY problem and I would suggest you just load the restaurants into your view as you get them. This will probably be a better user experience in most cases.
That being said, if you want to do what you are asking about, you can make it work by using $.all(). Essentially, create and return your deferred promise. Start with an empty list and for every key_entered event, push a new promise onto the list. Then, in your ready event callback, do a $q.all() on the list of promises and once they complete (in the then() of the promise), do the deferred.resolve().

Waiting for User input before continuing to Marionette Application next stage

My application needs a function to be called at initialize:after stage. After user has provided that input in function, i want application to go in start stage. But currently, it just go to all the 3 stages without waiting for input. Can anyone suggest how can i do acheive my desired functionality?
var app= new Marionette.Application();
app.on('initialize:before', function(options){
//do Something
});
app.on('initialize:after', function(options){
//do Something
//wait for User to give input before continuing to start stage.
});
app.on('start', function(options){
//start only when User provide input.
//do Something with input.
});
var options = {};
app.start(options);
This is less a Backbone/Marionette question and more of a pure JavaScript problem. If you don't care about usability, just use window.prompt and save yourself a lot of work.
If you're not able to use alerts, then things get more complicated. User inputs are usually done using some sort of form. Unfortunately, these are asynchronous operations, meaning you can't just halt JavaScript execution while you wait for the user to get out their glasses and look for their SSN. jQuery's Deferred library is a good tool to use to handle situations like these, but you'll need to rework your code a little.
In our project we've created a the concept of a Lifecycle that works roughly as follows:
Module.lifecycle = {
step1: function() {
var dfd = new $.Deferred().resolve();
// get user input from a custom dialog control
var dialog = new MyDailogControl("What do you want to do?");
dialog.onSuccess = dfd.resolve;
dialog.onFail = dfd.reject;
dialog.show();
return dfd.promise();
},
step2: function() { /* load some data from the server */ },
step3: function() { /* get even more user input... */ },
};
Next we have a Lifecycle Walker object that pushes the lifecycle through each state; it looks something like this (from memory; you'll want to test this...)
var Walker = function(lifecycle) {
this.lifecycle = lifecycle;
this._states = _.keys(this.lifecycle);
}
_.extend(Walker.prototype, Backbone.Events, {
start: function() {
this._index = 0;
this.moveNext();
},
moveNext: function() {
var step = this.states[this._index];
this.trigger('before:' + step);
$.when(this.lifecycle[step]())
.then(function() {
this.trigger('after:' + step);
this._index++;
if (this._active < this._states.length) {
this.moveNext();
}
});
}
});
Tying the two ideas together, you'll do something like:
var walker = new Walker(MyModule.lifecycle);
walker.on('before:step1', function() { /* do something amazing */ });
walker.on('before:step2', function() { /* do something fantastic */ });
walker.on('after:step3', function() { /* do whatever */ });
walker.start();
So, we've basically implemented a bastardized Command Pattern using deferreds to solve problems like this. We hook into module.start, but there's no reason you couldn't do something similar on app.start instead.

passing an array in a message from content script to background page in google chrome extension

I am writing a Google Chrome extension.
I want to pass a small array from a content script to background page in a message. Can I simply reference the array name or need I construct a JSON object from it first?
Here is the code:
IN THE CONTENT SCRIPT
var req;
var detailWin;
//drag off the f_foto class
var searchResult = document.getElementsByClassName("f_foto");
alert("Found Class f_foto "+searchResult.length+" times.");
//collect profile links
for (var i = 0; i<searchResult.length; ++i)
{
var profileLink=searchResult[i].getElementsByTagName("a");
profileLinks[i]=profileLink[0].href;
// alert(i+1+" of "+searchResult.length+" "+profileLinks[i]+" length of "+profileLinks[i].length);
}
for (var i = 0; i<searchResult.length; ++i)
{
//tell bkgd page to open link
chrome.extension.sendRequest({cmd: "openProfile", url: profileLinks[i]});
//BETTER TO SEND WHOLE ARRAY.
//LIKE THIS? chrome.extension.sendRequest({cmd: "openProfile", urlList: profileLinks});
//OR SHOULD I MAKE A JSON OBJECT OUT OF IT?
}
//IN THE BACKGROUND PAGE
var detailTabId = null;
var profileLinks = new Array();
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request.cmd == "openProfile") {
//IF RECEIVING AN ARRAY, PROCESS IT LIKE THIS?
// profileLinks= request.urlList;
// console.log=("Received "+ urlList.length + " links.");
chrome.tabs.create({url: request.url}, function(tab){
//save tab id so we can close this tab later
detailTabId = tab.id;
//profile tab is created, inject profile script
chrome.tabs.executeScript(tab.id, {file: "profile.js"});
});
}
});
An Array is a construct of a JSON object so there is no need to do anything other than what you are doing now.

Resources