Change element on page init of jquery mobile - javascript

I try to change slider properties on page init :
$(document).delegate('#my-page','pageinit', InitMyPage());
function InitMyPage() {
var today = new Date();
$("#my-slider").prop({
min: 1,
max: 50
}).slider("refresh");
}
It looks like on the page init $("#my-slider") still unknown.
When I try to get it on console at this point its look like this:
$("#year-slider")
[]
And I get error:
Uncaught TypeError: undefined is not a function
When can I change the elements (which event)?

This code:
$(document).delegate('#my-page','pageinit', InitMyPage());
calls InitMyPage and passes its return value into delegate, exactly the way foo(bar()) calls bar and passes its return value into foo.
To pass the function into delegate instead, remove the () from after it:
$(document).delegate('#my-page','pageinit', InitMyPage);
// No () here ----------------------------------------^
And I get error:
Uncaught TypeError: undefined is not a function
When can I change the elements (which event)?
That's because InitMyPage doesn't return anything, so the result of calling it is undefined, which is being passed into delegate. Later when the event occurs, apparently jQuery Mobile tries to call that undefined (which, not being a function, causes the error). I'm slightly surprised jQuery Mobile doesn't notice that and not try to call it, but... :-) Fixing the other thing will fix this.

Related

Cannot read property of undefined of an apparently NOT undefined - SOLVED

I am using a control of Telerik (AutoCompleteBox) which contains an embedded dropdown control that can be accessed through the property _dropDown. I am using the dropDownItemDataBound event to trigger the following code:
var autoComplete = $find("<%= RadAutoCompleteBox1.ClientID %>");
console.log(autoComplete._dropDown._items);
When I click over the [] in the console I get this (that is expected):
[]
0: b.RadAutoCompleteBox.DropDownItem
_attributes: c.AutoCompleteBoxAttributeCollection {_data: {…}, _keys: Array(0)}
_element: null
_template: null
_text: "Chevrolet TRAVERSE "
_value: "GM1"
Thus I supposed that I could do this:
var autoComplete = $find("<%= RadAutoCompleteBox1.ClientID %>");
console.log(autoComplete._dropDown._items[0]._text); // Chevrolet TRAVERSE
console.log(autoComplete._dropDown._items[0]._value); // GM1
Instead I get:
Uncaught TypeError: Cannot read property '_text' of undefined
It doesn't make sense to me because since autoComplete._dropDown._items is obviously an array (and it's NOT undefined!) I should be able to access it by indexing it and get the property contents. Not?
EDIT:
Following the suggestion of #ChrisG that mentioned that perhaps the arry was STILL empty when I tried to log the data to the console, I changed my code into the event to this (to give it a little time and see what happens):
waitAndDisplay();
function waitAndDisplay(timeout = 50) {
setTimeout(function () {
var autoComplete = $find("<%= RadAutoCompleteBox1.ClientID %>");
console.log(autoComplete._dropDown._items[0]._text);
}, timeout);
}
Indeed it worked however it doesn't seem to be a safe approach. Any idea on how to ENSURE that the data is fully loaded before to try to read it?
SOLUTION:
I was after the suggestion of #ChrisG on use a callback to data loaded and figured that I goofed in the documentation of the control because in fact there IS an event that triggers after the dropdown is fully loaded, so I will post the solution here. This way the callback function to be used is OnClientRequested and not the dropDownItemDataBound as I did initially:
function OnClientRequested(sender, eventArgs) {
var myarray = eventArgs.get_data();
console.log(myarray[0].Text);
console.log(myarray[0].Value);
}
It will return the proper data.

Javascript called by blazor code happens when DOM not yet ready?

I've a javascript function that has to create graph:
<script>
window.setGraph = (lab, ser) => {
console.log(document.getElementById("weather-chart"));
console.log(lab);
console.log(ser);
var chart = new Chartist.Line('#weather-chart', {
labels: lab,
series: ser
});
console.log("done");
return true;
}
</script>
This function is called by one of my blazor component:
protected override async Task OnInitAsync()
{
some-data-a = await RetrieveSomeData();
some-data-b = await RetrieveSomeOtherData();
JSRuntime.Current.InvokeAsync<bool>("setGraph", some-data-a, some-data-b);
}
Everything is executed, my console.log are called. But it appears that at this moment my element #weather-chart cannot be found, because I get this:
chartist.min.js:8 Uncaught TypeError: Cannot read property 'querySelectorAll' of null
at Object.c.createSvg (chartist.min.js:8)
at f.d [as createChart] (chartist.min.js:8)
at f.h (chartist.min.js:8)
AND
my console.log(document....) is returning null.
If I go to this page, I've the error, and if just after getting this error I do something like window.setGraph([1,2,3], [[1,2,3]]) in my chrome developer tools, everything is initialized correctly.
So what did I do wrong? Why chartist doesn't seems to be able to find the element?
It appears that blazor's databinding was taking some time to display the html. So basically after I set the _items, it was changing the template, but not fast enough for the line after this(not sure why, since there was an await).

Getting uncaught error in ember

When I'm doing the right click option for more than 5 (approx) times for certain task, it showing uncaught error as like below:
Uncaught TypeError: Cannot read property 'find' of undefined
at Class.<anonymous> (core.js:21487)
at fn (core.js:7779)
at DeferredActionQueues.flush (core.js:7723)
at Backburner.end (core.js:7738)
at Backburner.run (core.js:7748)
at executeTimers (core.js:7824)
at core.js:7822
In that Place I'm having the below code:
Ember.run.later(view, function () {
this.$().find('menu-item:eq(0)').focus();
}, 125);
Can anyone please suggest me why this error is coming and I need to avoid this error while right clicking the task for "n" number of time also. I'm new to the ember. Your help will be appreciate. Thanks in advance.
Thats a simple javascript issue. In the second line this.$() returns undefined, and so it can't call .find on undefined.
More interesting is why this.$() is undefined. Probably you have this code inside a component, and try to access the local jQuery instance. However you call it inside an anonymous function(){}, which breaks your this-context (because it gets a new one).
The best solution here is to use an arrow function:
Ember.run.later(view, () => {
this.$().find('menu-item:eq(0)').focus();
}, 125);
this prevents the outer this context, which is nice. Another options is to save this:
const self = this;
Ember.run.later(view, function () {
self.$().find('menu-item:eq(0)').focus();
}, 125);
Or you can .bind(this):
Ember.run.later(view, (function () {
this.$().find('menu-item:eq(0)').focus();
}).bind(this), 125);
I can definitely recommend the first option, especially when using ember(-cli) which gives you transpilation anyway.

TypeError: $(...) is null - how to use noconflict()

i get error TypeError: $(...) is null.
<script>
$('w_pages').observe('change', function(){
parent.preview.location = 'W/preview/<?=$page['parent_id'] ?>/?p='+$('w_pages').value;
});
$('w_layout').observe('click', function(){
parent.preview.Tiny.showURL('S/layout/'+$('w_pages').value+'?ajax=true',true)
});
</script>
i read that it is because of a conflict. how do i wrap this in noConflict()
There is no conflict here.
You are using the dollar function of Prototype, which returns a reference to the element with id equal to its argument. If no such element exists in the page it returns null, which in turn causes the TypeError.
I don't know why no such element exists in your page or how to make the JS work like it should, but you can avoid the immediate error by checking the return value before calling methods on it:
var wPages = $('w_pages');
if (wPages) {
wPages.observe('change', function(){
parent.preview.location =
'W/preview/<?=$page['parent_id'] ?>/?p='+wPages.value;
});
}
// The same for w_layout
i fixed it. i was indeed missing the element. thanx for putting me in the right direction.

Having IE Issues When Passing Object By Ref. and Dynamically Adding Properties

So, I've created a function to do some error checking on an XML file that I recieve from an AJAX call. Part of the validation is that the function then builds out an object for easy access while I process that data into a form. In FF, works like a charm. IE dies with the error:
Object doesn't support this property or method
Here is the function (minus the un-important bits):
function checkReceiveXMLTagString( doc, messageObject, tag ) {
var tag_nodes = doc.getElementsByTagName( tag );
...do some error checking...
messageObject[tag] = tag_str; <-- error occurs on this line
return true;
}
Here is an example of how the function is call:
if ( checkReceiveXMLTagString( messageObject.Name[0], messageObject.Name[0], "First" ) ) {
...process messageObject.Name[0].First...
}
Like I said, FF has no issues. Safari loads the pages as well. IE has issues.
Thanks!
Looks like something is making messageObject be null or undefined
If the error is on this line:
messageObject[tag] = tag_str;
Then, the only two ways I know of that that can cause an error are:
messageObject is not an object that you can set properties on (null or undefined are the most likely ways that would happen)
tag is null or undefined
Since I see that your code calls this function hundreds of times so you can't effectively just break on it, I'd suggest you put in some defensive coding to check for those conditions and output something to the debug console to identify what the state is when the problem occurs. You can even trigger a conditional breakpoint with code like this:
if (!messageObject || !tag) {
debugger;
}
In the toughest cases, you can put an exception handler around it and break when the exception is thrown:
try {
messageObject[tag] = tag_str;
} catch(e) {
debugger;
}
Both of these will allow you to capture the condition in the debugger and examine all your parameters at the time of the error.

Categories