Why does the ainteger setting not work right? - javascript

I have two versions of code. The first version doesn't work, the second version does. Why does the first version's ainteger setting not work right? It is suppose to cause "Player One" and "Player Two" to be displayed above the buttons on the second register button press. I have included the code below.
To be more specific the program is supposed to call the server's register function when the register button is pressed. The server sets the value in the html, using the server's setinteger() when its integer value is one. When the client's ainteger is two (second time register key was pressed,) the event handler will call the server's printthename() function. This in turn calls the client's printname() and printname2() and displays the names. These names are not being displayed!
By tracing the error, when the button is hit twice , the register button event is not breaking in the register buttons event handler, and the block for the ainteger does not seem to be calling the printthename(). It does however show up in the server's register function when the server's integer value is one.
The program uses SignalR and two explorer tabs with Visual Studio 2019.
I have tried changing the code, slimmed it down, made it simple, and traced. And printthename() called from setinteger() is a version that works.
The GitHub link is : https://github.com/Joshei/signalr1
Branch 3 : new version, works.
Branch 4 : old version, doesn't work (doesn't display the names.)
The Visual Studio version has comments to explain that there is no way this is causing any problems.
/////////////////////////////////////HUB://///////////////////////////////////
public class ChatHub : Hub
{
private static readonly List<clients> ClientList = new List<clients>();
public void printthename()
{
string name = "";
if (whoseturn == 0)
{
name = "Player one ";
Clients.Client(ClientList[0].ConnectionId).printname(name);
name = "Player two ";
Clients.Client(ClientList[1].ConnectionId).printname2(name);
}
}
public void register(string name1)
{
clients A_Client = new clients();
A_Client.ConnectionId = Context.ConnectionId;
A_Client.Name = name1;
ClientList.Add(A_Client);
if (integer == 0)
{
integer = integer + 1;
}
else if (integer == 1)
{
Clients.Client(ClientList[1].ConnectionId).setinteger();
Clients.Client(ClientList[0].ConnectionId).setinteger();
}
}
}
/////////////////////////////////////HTML CLIENT://///////////////////////////////////
$(function () {
var ainteger = "0";
$("#Join").click(function () {
$('#Join').hide();
$('#Name').hide();
chat.server.register("a");
if (ainteger == "1") {
chat.server.printthename();
}
});
chat.client.setinteger = function () {
ainteger = "1";
};
});
Thank you, I have been trying to get this working since November 30.

Related

Code behind Content editor button for Experience editor button

Is it possible to use a code behind of a command used for ribbon button in content editor as a request for experience editor button? We want to stick to SPEAK and not make any changes to Sitecore.ExperienceEditor.config.
After creating new button in Experience editor, telling .js to call NewCommand request by
Sitecore.ExperienceEditor.PipelinesUtil.generateRequestProcessor("ExperienceEditor.NewCommand");
that was referenced in Sitecore.ExperienceEditor.Speak.Requests.config as
<request name="ExperienceEditor.NewCommand" type="Sitecore.Starterkit.customcode.MyCommand,MyProject"/>
nothing happens and logs say
ERROR Could not instantiate speak request object,
name:ExperienceEditor.NewCommand,
type:Sitecore.Starterkit.customcode.MyCommand,MyProject`
Do we have to import PipelineProcessorRequest as suggested by some tutorials or is there a way to use our existing code?
Have you seen this blog post on adding custom SPEAK command buttons to Sitecore 8 Experience Editor?
https://doc.sitecore.net/sitecore%20experience%20platform/the%20editing%20tools/customize%20the%20experience%20editor%20ribbon
Otherwise if that doesn't achieve what your looking for, it might be worth trying to standard SPEAK application way of triggering a button, In a SPEAK application you can call a JavaScript function from a button click using this code.
javascript:app.FunctionName();
In the core DB update the click field on your button to call JavaScript with the javascript: prefix. Does this allow you to trigger your JavaScript?
I was able to use my existing control using guidelines from:
http://jockstothecore.com/sitecore-8-ribbon-button-transfiguration/
Relevant pieces of the old command:
if (args.IsPostBack)
{
// act upon the dialog completion
if (args.Result == "yes")
{
Context.ClientPage.SendMessage(this, "item:load(...)");
}
}
else
{
// trigger the dialog
UrlString url = new UrlString(UIUtil.GetUri("control:CopyLanguage"));
url.Add("id", item.ID.ToString());
url.Add("lang", item.Language.ToString());
url.Add("ver", item.Version.ToString());
SheerResponse.ShowModalDialog(url.ToString(), true);
args.WaitForPostBack();
}
The redressed command:
define(["sitecore"], function (Sitecore) {
Sitecore.Commands.ScoreLanguageTools = {
canExecute: function (context) {
return true; // we will get back to this one
},
execute: function (context) {
var id = context.currentContext.itemId;
var lang = context.currentContext.language;
var ver = context.currentContext.version;
var path = "/sitecore/shell/default.aspx?xmlcontrol=CopyLanguage" +
"&id=" + id + "&lang=" + lang + "&ver=" + ver;
var features = "dialogHeight: 600px;dialogWidth: 500px;";
Sitecore.ExperienceEditor.Dialogs.showModalDialog(
path, '', features, null,
function (result) {
if (result) {
window.top.location.reload();
}
}
);
}
};
});

Playframework 2.1.2 how to prevent scala function calls on template load?

I have a number of Scala function calls in my template file, unfortunately they are getting automatically called during template loading for some reason. How can I prevent those from being called?
My intention is they are called only after certain click events. And I would get a huge performance increase during template load (26s vs 3s).
I have a DataLoader Java object, which is being called from template and does the reading of values from database. The relevant parts of DataLoader:
public void SetAllowLoading() {
System.out.println("DataLoader SetAllowLoading > ");
allowLoading = 1;
}
public void SetDisAllowLoading() {
allowLoading = 0;
}
public void debugdebug(String text) {
System.out.println(text);
}
public List<Double> loadAreaLengthData() {
List<Double> areaLengthArray = new ArrayList<Double>();
System.out.println("DataLoader OUT loadAreaLengthData > ");
if (allowLoading > 0) {
System.out.println("DataLoader IN loadAreaLengthData > ");
areaLengthArray.add(Component.getPipeLenghtsAccordingToRelativeFloorAreaMeters(0, 11));
areaLengthArray.add(Component.getPipeLenghtsAccordingToRelativeFloorAreaMeters(11, 21));
areaLengthArray.add(Component.getPipeLenghtsAccordingToRelativeFloorAreaMeters(21, 31));
areaLengthArray.add(Component.getPipeLenghtsAccordingToRelativeFloorAreaMeters(31, 41));
areaLengthArray.add(Component.getPipeLenghtsAccordingToRelativeFloorAreaMeters(41, 51));
}
return areaLengthArray;
}
If loading is not allowed, the loading method doesn't read from database.
Then the necessary parts from template (pipeIndex.scala.html)
$("#info2").on("click", function() {
if($(this).hasClass("selected")) {
$("#info2").html('#Messages("consequence.floor") (m<sup>2</sup>/m)');
#loader.debugdebug("debugFloorAreaDESELECT");
deselectArea();
} else {
$(this).addClass("selected");
$(".chartsarea").slideFadeToggle(function() {
#loader.debugdebug("drawFloorAreaChart()");
var sarea = new Array();
var i = 0;
var number = 0;
#for(s <- loader.loadAreaLengthData) {
number = Math.round(#s);
if (!isNaN(number))
sarea[i] = Math.round(number / 1000);
else
sarea[i] = 0;
i++;
}
var ticksArea = ["0-10", "10-20", "20-30", "30-40", "40-50"];
areaObj = {
// Only animate if we're not using excanvas (not in IE 7 or IE 8)..
animate: !$.jqplot.use_excanvas,
seriesDefaults:{
renderer:$.jqplot.BarRenderer,
pointLabels: { show: true }
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticksArea
}
},
highlighter: { show: false }
}
plot3 = $.jqplot('chartarea', [sarea], areaObj);
$("#info2").focus();
$("#info2").html('#Messages("consequence.hide.floor")');
});
}
return false;
});
function deselectArea() {
$(".chartsarea").slideFadeToggle(function() {
$("#info2").removeClass("selected");
});
}
My question is how that "on" click handler is called automatically at every pageload? How can I prevent the calling during pageload?
I used for showing/hiding functionality the example at jsfiddle: anotherjsfiddle However I used multiple click handlers (here is shown only for info2 element). And I changed that jquery "live" event method to "on", because "live" is deprecated.
If I understand you right you are asking why the debug messages (e.g. #loader.debugdebug("debugFloorAreaDESELECT");) are getting called on each site load and not only on click..?
This is because Play templates are getting rendered on the server side, i.e. as soon as template.render() will get called in the controller. This affects all the the Scala parts in the template (i.e. everything starting with #)
If you would like to debug on the client side you could use JavaScripts console.log()
Although previous answer describes it I'll use a phrase which I repeated several times already:
Play template is ServerSide technology, so it's rendered during Play pass (i.e. if your views will be cached for 1 month you will have 1 month old values in the view), JavaScript is ClientSide. That means - that you can't mix it like this.

New to javascript but my function works wrong in firefox

I'm just getting into javascript and so far enjoying the logic behind it but i have an issue with Firefox. basicly im generating my javascript from within a php function and its a NON SECURE pin code auth script.
So my php creates a call that passes variables pin number included, when called a modal popup with pinpad opens and the user inputs 4 digits, the pinpad onclick function adds the digits into a password field and after 4 clicks it compares it to a hidden field on the pinpad form, if it matches it calls another generated function to complete the success action, if no match pinpad frame turns red and a bypass button is enabled or they can try again.
This all works fine in Chrome, Opera and even IE but in Firefox it calls the success function after 4 digits even if they don't match the pin field.
Why could this be? Below is the function, but please remember I'm new so it could possibly be better written.
function add(text) {
var TheTextBox = document.pinform.elements['pin'];
var pincheckbox = document.pinform.elements['pincheck'];
var sidbox = document.pinform.elements['sid'];
TheTextBox.value = TheTextBox.value + text;
if (TheTextBox.value.length == 4) {
if (pinform.pin.value == pinform.pincheck.value) {
var pinn = document.getElementById('sid').value;
eval('pinpass' + pinn + '();');
} else {
document.getElementById("bypass").innerHTML = "Bypass";
document.getElementById("bypass").disabled = false;
document.getElementById("calc").style.backgroundColor = 'red';
TheTextBox.value = '';
return false;
}
}
}
Found the answer by trial and error as usual lol.
i need to add document. in front of pinform.pincheck.value and pinform.pin.value
Thanks for the help offered.
Nick
if (TheTextBox.value.length == 4) {
if (doucment.pinform.pin.value == document.pinform.pincheck.value) {
var pinn = document.getElementById('sid').value;
eval('pinpass' + pinn + '();');
} else {

display message javascript while a calculation is being made

I have been looking around and I cannot seem to figure out how to do this, although it seems like it would be very simple.(mobile development)
What I am trying to do is display a message (kind of like an alert, but not an alert, more like a dialog) while a calculation is being made. Simply like a Loading please wait. I want the message to appear and stay there while the calculation is being done and then be removed. I just cannot seem to find a proper way of doing this.
The submit button is pressed and first checks to make sure all the forms are filled out then it should show the message, it does the calculation, then hides the message.
Here is the Calculation function.
function scpdResults(form) {
//call all of the "choice" functions here
//otherwise, when the page is refreshed, the pulldown might not match the variable
//this shouldn't be a problem, but this is the defensive way to code it
choiceVoltage(form);
choiceMotorRatingVal(form);
getMotorRatingType();
getProduct();
getConnection();
getDisconnect();
getDisclaimer();
getMotorType();
//restore these fields to their default values every time submit is clicked
//this puts the results table into a known state
//it is also used in error checking in the populateResults function
document.getElementById('results').innerHTML = "Results:";
document.getElementById('fuse_cb_sel').innerHTML = "Fuse/CB 1:";
document.getElementById('fuse_cb_sel_2').innerHTML = "Fuse/CB 2:";
document.getElementById('fuse_cb_result').innerHTML = "(result1)";
document.getElementById('fuse_cb_res_2').innerHTML = "(result2)";
document.getElementById('sccr_2').innerHTML = "<b>Fault Rating:</b>";
document.getElementById('sccr_result').innerHTML = "(result)";
document.getElementById('sccr_result_2').innerHTML = "(result)";
document.getElementById('contactor_result').innerHTML = "(result)";
document.getElementById('controller_result').innerHTML = "(result)";
//Make sure something has been selected for each variable
if (product === "Choose an Option." || product === "") {
alert("You must select a value for every field. Select a Value for Product");
**************BLAH************
} else {
//valid entries, so jump to results table
document.location.href = '#results_a';
******This is where the message should start being displayed***********
document.getElementById('motor_result').innerHTML = motorRatingVal + " " + motorRatingType;
document.getElementById('voltage_res_2').innerHTML = voltage + " V";
document.getElementById('product_res_2').innerHTML = product;
document.getElementById('connection_res_2').innerHTML = connection;
document.getElementById('disconnect_res_2').innerHTML = disconnect;
if (BLAH) {
}
else {
}
populateResults();
document.getElementById('CalculatedResults').style.display = "block";
} //end massive else statement that ensures all fields have values
*****Close out of the Loading message********
} //scpd results
Thank you all for your time, it is greatly appreciated
It is a good idea to separate your display code from the calculation code. It should roughly look like this
displayDialog();
makeCalculation();
closeDialog();
If you are having trouble with any of those steps, please add it to your question.
Computers are fast. Really fast. Most modern computers can do several billion instructions per second. Therefore, I'm fairly certain you can rely on a a setTimeout function to fire around 1000ms to be sufficient to show a loading message.
if (product === "Choose an Option." || product === "") {
/* ... */
} else {
/* ... */
var loader = document.getElementById('loader');
loader.style.display = 'block';
window.setTimeout(function() {
loader.style.display = 'none';
document.getElementById('CalculatedResults').style.display = "block";
}, 1000);
}
<div id="loader" style="display: none;">Please wait while we calculate.</div>
You need to give the UI main thread a chance to render your message before starting your calculation.
This is often done like this:
showMessage();
setTimeout(function() {
doCalculation();
cleanUp()
}, 0);
Using the timer allows the code to fall through into the event loop, update the UI, and then start up the calculation.
You're already using a section to pop up a "results" page -- why not pop up a "calculating" page?
Really, there are 4,000,000 different ways of tackling this problem, but why not try writing a "displayCalculatingMessage" function and a "removeCalculatingMessage" function, if you don't want to get all object-oriented on such a simple thing.
function displayCalculatingMessage () {
var submit_button = getSubmitButton();
submit_button.disabled = true;
// optionally get all inputs and disable those, as well
// now, you can either do something like pop up another hidden div,
// that has the loading message in it...
// or you could do something like:
var loading_span = document.createElement("span");
loading_span.id = "loading-message";
loading_span.innerText = "working...";
submit_button.parentElement.replaceChild(loading_span, submit_button);
}
function removeCalculatingMessage () {
var submit_button = getSubmitButton(),
loading_span = document.getElementById("loading-message");
submit_button.disabled = false;
loading_span.parentElement.replaceChild(submit_button, loading_span);
// and then reenable any other disabled elements, et cetera.
// then bring up your results div...
// ...or bring up your results div and do this after
}
There are a billion ways of accomplishing this, it all comes down to how you want it to appear to the user -- WHAT you want to have happen.

Play Framework redirect not always work. Bug or my fault?

i am trying to redirect a user to another page in my play project. The problem is, the redirect works quite well in one view, but it doesnt work in another view.
The strange thing is, when i look at the console -, i can see that system has loaded the view (i can see this by setting system.out.println() command" but i cant see that happening in the browser view.
Working Code:
public static void deleteMessages(boolean[] chbox)
{
System.out.println("Checkbox count: "+chbox.length);
String[] referer =Request.current().headers.get("referer").toString().split("/");
String mailbox = referer[referer.length-2];
String pageNumber ="/"+ referer[referer.length-1];
for(int i = 0; i<chbox.length;i++)
{
String id=params.getAll("hdnchbox")[i].toString();
if(mailbox.equals("inbox"))
{
MessageInbox m = MessageInbox.findById(Long.parseLong(id));
m.delete();
}else
{
MessageOutbox m = MessageOutbox.findById(Long.parseLong(id));
m.delete();
}
}
show(mailbox,Integer.parseInt(pageNumber));
}
Not Working Code:
public static void deleteMessage(Long id, String mailbox)
{
if(mailbox.toLowerCase().equals("inbox"))
{
MessageInbox msg = MessageInbox.findById(id);
msg.delete();
}
else
{
MessageOutbox msg = MessageOutbox.findById(id);
msg.delete();
}
System.out.println("Redirect URL: "+"/Messages/"+mailbox);
String redirectURL = "/Messages/"+mailbox;
show(mailbox,null);
}
The show void:
public static void show(String messageBoxName,Integer pageNumber)
{
if(pageNumber == null)
{
System.out.println("pagenumber null");
pageNumber = 0;
}
List<UserMessage> msgs = messageList(pageNumber,messageBoxName);
System.out.println("The page has loaded");
render(pageNumber,msgs,messageBoxName);
}
The strangest part is i can both see the "The page has loaded" message in the system console, but i can see it in the browser window.
is it a bug, or am i doing something wrong?
(passing null value to show() works i tried that)
This may be a bug with localVariables, I had a similar problems so times ago. Even if I reassign a variable like pageNumber, I got null in my template
Try calling "show(mailbox, 0)" instead of "show(mailbox,null)" to see if it solves your problem
i've ended up redirecting with jquery instead of play redirect command. I think this is a bug in play framework. i can see the response html in firebug but no luck on the browser screen.

Categories