Javascript seems to get out of the control flow - javascript

I have a problem and I don't know how to fix it ... in the following code - the control seems to never reach the changePage command! I guess that's a problem of the control flow in the addToGlobal function ... is this possible?
$(document).ready(function() {
var globalData = {};
function addToGlobal(name, value) {
globalData[name] = value;
};
$('#tempform').submit(function (event) {
event.preventDefault();
console.log("preventDefault Temp")
var form = $(this);
// add to globalData
addToGlobal("TemperatureU", form.data('clicked'));
$.mobile.changePage('#page2', {transition: 'slide'});
});
});

You have a small syntax error. You are missing a closing ) at the end of the ready handler.
The first step for any JS problem should be to check the console for any error messages. I ran your code, and saw the syntax error in the console showing a missing parenthesis.

The only reason that addToGlobal wouldn't run is if form.data('clicked') is throwing an error. I suggest adding a few more console.logs around to see what's really going on.
console.log(form.data('clicked'));
addToGlobal("TemperatureU", form.data('clicked'));
console.log(globalData);

Related

Kendo controls don't seem to be ready in document.ready

I am using the kendo kendoNumericTextBox.
The kendo js libraries are included before the following.
I am trying to store a reference to the actual input for later use like this:
$(document)
.ready(function () {
//Wire up the elemets with selectors
$eventGrid = $("#jsGrid");
$bedInput = $('#bed');
$dateInput = $('#date');
$operatingTimeInput = $("#operatingTime").data("kendoNumericTextBox"); <-- ERROR OCCURS HERE
$plannedDowntimeInput = $("#plannedDowntime").data("kendoNumericTextBox");
fetchDayData(currentBed(), currentDate());
})
Uncaught TypeError: Cannot read property 'value' of undefined
However when stepping through, both $operatingTimeInput and $plannedDowntimeInput are undefined. If I later do these assigments manually in the console, everything works as expected.
Now, I seem to remember there being an event similar to document.ready() but specifically for kendo. Though, For the life of me, I can't find it...
Any thoughts?
EDIT 1
The fields are being initialized in a razor view like this:
#(Html.Kendo().NumericTextBox()
.Name("operatingTime")
.Max(24)
.Min(0)
.Step(0.05)
.HtmlAttributes(new { #id = "operatingTime" })
)
So as you can see, I have no control over when the textbox is actually "created". That's why I'm looking for a way to get the instance created by the html helper.
One way which I tried to accomplish is like :
$(document)
.ready(function () {
$("#operatingTime").ready(function(){
setTimeOut(function(){
if($("#operatingTime").data("kendoNumericTextBox")){
//Wire up the elemets with selectors
$eventGrid = $("#jsGrid");
$bedInput = $('#bed');
$dateInput = $('#date');
$operatingTimeInput = $("#operatingTime").data("kendoNumericTextBox"); <-- ERROR WILL NOT OCCUR HERE
$plannedDowntimeInput = $("#plannedDowntime").data("kendoNumericTextBox");
fetchDayData(currentBed(), currentDate());
}
},1000);
});
})
Since I had comfort of waiting for 1 second, I went with this logic. let us know if something else has worked out for you.

assertExists with if-else statement

I use this code:
var x = require('casper').selectXPath;
...
casper.waitForSelector(x("//a[contains(#id,'cell_13_1')]"), function() {
this.test.assertExists(x("//a[contains(#id,'cell_13_1')]"), 'Clickable');
this.click(x("//a[contains(#id,'cell_13_1')]"));
});
I am trying to use if-else with assertExists to click another element if the first is not there:
casper.waitForSelector(x("//a[contains(#id,'cell_13_1')]"), function() {
if(this.test.assertExists(x("//a[contains(#id,'cell_13_1')]")==="PASS"){
this.click(x("//a[contains(#id,'cell_11_1')]"));}
else{
this.click(x("//a[contains(#id,'cell_22_1')]"));
}
});
But that does not seem to work. How would one do it correctly?
That's exactly what casper.exists() is for. You can also explicitly pass or fail some things:
casper.waitForSelector(x("//a[contains(#id,'cell_13_1')]"), function() {
if(this.exists(x("//a[contains(#id,'cell_13_1')]")){
this.test.pass("Clickable");
this.click(x("//a[contains(#id,'cell_11_1')]"));
} else {
this.test.fail("Clickable");
//this.click(x("//a[contains(#id,'cell_22_1')]"));
}
});
This code is equivalent to your first snippet. Comment the fail() call and uncomment the last click in order to get your "intended" behavior.
Btw, it doesn't make sense to fail some assertion and still continue with the script. You have to think about what exactly you want to test and what part of your script is supposed to be navigation to the component under test.

How do I get the Yammer Embed Feed Event listeners to work?

From the documentation, all you need to hook onto a Yammer embed feed event is to use:
yam.on(eventId, callbackFunction, [context]);
Which I've done using the eventIDs they have supplied, so my code ends up looking like this:
<script type="text/javascript">
yam.connect.embedFeed({
container: "#embedded-comments",
network: "mynetwork",
feedType: "open-graph"
});
function alertMe() {
alert("Loading Completed!");
}
var nothing = "";
yam.on('/embed/feed/loadingCompleted', alertMe(), nothing);
</script>
Only that the alertMe() function gets called immediately, before the page has even loaded. Changing the eventID to something invalid shows the same behaviour, so I'm starting to think I'm missing something here.
Any ideas what could be causing the events to fire immediately?
Got it working by passing alertMe as a reference (removing the parentheses). I was seeing the events firing instantly due to them being executed as they were being read.
Quite a silly mistake, but being a javascript beginner I'm bound to make a lot of these :)
try this.
yam.on('/embed/feed/loadingCompleted', alertMe, nothing);

Pure JS: Listen for onchange event?

This is giving me "4: Uncaught SyntaxError: Unexpected token ILLEGAL":
(function() {
var select = document.getElementById('select-card');
​select.onchange = function() { };
})();
What should I be doing differently?
I expect that you have an element with id select-card. Your code is otherwise fine.
But you should be using.
select.addEventListener("change", function(){ } );
Edit the code to this: select.onchange = (function() { });
Whenever you're doing a function expression and calling it immediately, you need those parens because there's a parsing ambiguity otherwise.
I couldn't wrap my head around this. The code is correct however is was bugging still. Found it, it appeared when I converted my test page from UTF8 to ANSI:
There is a incorrect return/character in your code. That is causing the bug.

log errors with stack trace in javascript

I'm trying to log javascript errors on a productive site. So far it worked quite well with the following code included in the site:
function catcherr(errorMessage, url, line) {
var parameters = "msg=" + escape(errorMessage)
+ "&url=" + escape(url)
+ "&line=" + escape(line);
new Image().src = "/error.gif?" + parameters;
return false;
};
window.onerror = catcherr;
I'm trying to add a stack trace to the errors to get more information. This basically works with the following idea including into the function above:
try { i.dont.exist += 0; } // does not exist - that's the point
catch (e)
{
if (e.stack) // Firefox
{
// do some stuff
I use jquery, a simple example:
<script type="text/javascript">
jQuery(document).ready(function() {
p.foo += 1; // this should throw an error
// do stuff
});
</script>
The funny part is, that when I have an error inside the "ready" function of jquery, the part "try { i.dont.exist += 0; }" does not throw any exception anymore and the engine stops without any error.
With the example above, and catcherr extended as follows, only "1" gets alerted:
function catcherr(errorMessage, url, line) {
try { alert(1); i.dont.exist += 0; alert(4);} catch(e) { alert(5);}
alert(2);
var parameters = "msg=" + escape(errorMessage)
// ...
}
Anyone having an idea why this breaks, when an error occurs inside the "ready" function of jquery?
I don't know why you have that problem (it looks very weird and I don't think its a problem with JQuery eating your exceptions, as your alert(1) wouldn't have fired), but I did want to mention your use of Error.stack - when the onerror event gets called, you do not have the stack context of the original error, so getting a stack trace at that point (by catching your own error) will not yield a meaningful stack.
But back to a real answer - instead of simulating a problem by writing specifically broken code so you can catch the error, how about just directly throwing an error? The first line in your onerror handler could be:
try { throw new Error("dummy"); } catch (e) { alert(e.stack); }
This is valid code which will more likely not cause you problems.
Most likely jQuery is wrapping the callback in its own try/catch and ignoring the error.
Try a different exception inside the try/catch.
like a=1/0 or baddarr[5]='bad' and see if those trigger exceptions.
Sometimes "Object Not Found" errors may be as a result of objects not being loaded yet, and there might be different handling for those than other exceptions.

Categories

Resources