Retrieving jQuery.data() values from within setInterval - javascript

I've been stuck on this problem for a while now. I'm using jQuery's .data() method to store state in a plugin I'm writing. Everything works fine, except for when I try to retrieve these data values from within a setInterval block. I am able to see the jQuery object inside the setInterval block, but I'm not able to see values stored by the data() method.
tminusStart: function() {
return this.each(function() {
var $tminus = $(this).data("tminus.state", "running");
var intervalId = setInterval(function(tm) {
if ($tminus.tminusIsRunning()) {
$tminus.tminusDecrementCounter();
$tminus.data("tminus.settings").tick_event();
if ($tminus.tminusTimeRemaining() <= 0) {
$tminus.data("tminus.settings").expiration_event();
}
$tminus.text(tminus.tminusTimeRemaining);
}
else {
clearInterval(intervalId);
}
}, 1000, $tminus);
});
}
In the above code, the $tminus does return the jQuery object alright, but the calls to the functions - which are calling the .data() method - return undefined; so does the .data("tminus.settings") call.
Any help in understanding why .data() isn't working here would be greatly appreciated.
Rewrite of function removing cruft:
tminusStart: function() {
var tminus = this;
tminus.data("tminus.state", "running");
return this.each(function() {
console.log(tminus.data("tminus.state")); // "running"
var intervalId = setInterval(function() {
console.log(tminus.data("tminus.state")); // undefined
}, 1000);
});
}
I need to know why it's undefined in the setInterval block

What are tminusIsRunning and tminusDecrementCounter? Did you mean to call that under $tminus? Unless you're extending jQuery, those calls are going to error out. If you're using Chrome, check the Javascript Console, you should see something like: "Uncaught TypeError: Object [object Object] has no method 'tminusIsRunning'"

.data() doesn't work with xhtml + IE (see note in docs).
Alternatively, This looks like a jQ extension, so watch out for that. jQuery has a (IMO) bad habit of aliasing this all over the place. Make sure you don't have a dependency on this being something different than what it is. I suggest installing firebug and using console.log to log this in both the place where you set the value, and where you access it. If it's not the IE issue, I suspect this would locate it.

Finally figured it out. I'm using jasmine to test drive this and the jasmine-jquery library has a fixtures piece which I'm apparently not using correctly. I tested the code in a webpage and everything is now working according to plan. Now I just have to make sure all my tests are passing.
I won't accept my own answer since I didn't provide the necessary information to begin with. I appreciate everyone's time on this. I really wish I could have accepted someone's answer.

Related

How to modify results from a read-only ng-app?

I apologize if this is a duplicate, just haven't been able to find anything close to this myself.
The company I work for has an online reporting system that is run by an ng-app applied directly to the body tag. I have been tasked with modifying the result that returns from this ng-app. Following code is called using onload attached to the body tag.
function getElements(){
var list;
list = document.getElementsByClassName("neutral");
[].forEach.call(list, function (listItem) {
addNeutral(listItem);
});
...
Basically, trying to find anything with class "neutral" and apply results from another function to it. The addNeutral function is basically just
element.classList.add("neutralHighlight");
This code seems to run and gathers the correct list of elements, but the new class is never added and no errors occur. So long story short, is there any way to modify the output of a ng-app using code separate from the ng-app itself? Any guidance would be greatly appreciated.
Update 3/5/20
So I implemented Shaun's response and it still isn't working properly. With some debug messages, I can see that it collects the "list" variable as an HTMLCollection. The forEach function doesn't seem to even trig
function getElements(){
var list;
list = document.getElementsByClassName("neutral");
console.log(list); //Debug - Shows in console
[].forEach.call(list, function (listItem) {
console.log(listItem); //Debug - Does not show in console
addNeutral(listItem);
});
}
function addNeutral(element){
angular.element(element).addClass("neutralHighlight");
console.log("!!!end addNeutral"); //Debug - Does not show in console
}
Update 3/9/20 -SOLUTION-
Application is returning the HTML Collection, but it displays with a length of 0 (still displays the objects, but I think that's a Firefox console thing). When trying to loop through the list items, it returns null for the first item, so the function is still being called before the Angular app loads completely.
That being said, I messed around with things a bit this morning and came to a solution! I ended up using the setInterval function with a 5 second interval (since I need it to update, I may change this to optimize it later by adding onChange items to the objects I grab initially). The setTimeout that was proposed would have worked with a delay added to it. This probably isn't the most elegant solution, and there's probably a better way to do it, but this works for anyone interested.
function getElements(){
var list;
list = document.getElementsByClassName("neutral");
for (i = 0; i <= list.length; i++){
var listItem = list.item(i);
addNeutral(listItem);
}
}
function loadFunction(){
setInterval(function(){getElements()}, 5000);
}
I added <script>loadFunction()</script> right before the closing HTML tag to execute.
Update 4/21/20 -IMPROVED SOLUTION- CSS Attributes
So this is a bit specific to my scenario, but I wanted to include it for anybody else who may come across this in the future. I was actually able to accomplish this entirely with CSS attribute selectors. The tags that I wanted to edit all had specific titles assigned to them via the ng-app provided from the company, so I was able to use CSS selectors like div [title~="NotReadyForNextCall"]{<custom styling here>} to select any block that included an agent who was not ready for their next call. This is a much better solution in terms of resources required to operate and overall performance, so I hope it helps anybody looking at this down the line!
You might be able to get around this by using the angular object in your code and adding the class on an angular.element instead. AngularJS doesn't use a virtual DOM but it does use its own node references (which is what makes it so tricky to work with outside of the framework, as Lex pointed out in the comments of your question). Try:
angular.element(element).addClass("neutralHighlight");
Yes, you have access to angular outside of the app! And a last note, addClass() is available on angular.element because AngularJS comes with jqLite.
Further investigation
It looks like the above solution works if the class 'neutral' is being added in angular via the class attribute, but it looks like your app may be adding it programmatically with the ng-class directive after the DOM has rendered.
I wrapped your getElements() function in a setTimeout():
setTimeout(getElements);
This is unfortunately not a guarantee that the ng-class update will have taken place, but what it does is it executes the function after the previous digest cycle has completed and that appears to be working.
An even safer solution would be to use document.ready but again with the angular.element wrapper. This will ensure the initial DOM state has been rendered by AngularJS, including applied directives:
angular.element(document).ready(function() {
getElements();
});
EDIT: Update 3/9/20 -SOLUTION-
The solution proposed in the answer is almost identical to the setTimeout() answer given here. The only difference is setInterval() will keep executing the code every 5 seconds until you tell it to stop.
You can do this with the following:
var loadFunction = setInterval(function() {
var el = getElements();
if (el) clearInterval(loadFunction);
}, 5000);
And just return a bool in your getElements() like so:
function getElements() {
var list;
var found = false;
list = document.getElementsByClassName("neutral");
[].forEach.call(list, function (listItem) {
addNeutral(listItem);
found = true;
});
return found;
}
See: codepen.io/shaunetobias/pen/KKpXRxq

Replacement for deprecated dijit/_Widget.getDescendants function?

I am using Dojo 1.9.1 and lodash.compat 1.3.1.
I am attempting to replace the deprecated dijit/_Widget.getDescendants() function. The deprecation warning says to use getChildren() instead, but that does not recurse.
This is what I have so far. It works fine in Chrome and Firefox, but results in an unhelpful [object Error] in IE7.
function get_widget_descendants(parent_widget) {
return _(query("[widgetid]", parent_widget.domNode))
.map(registry.byNode)
.value();
}
Here is a JSFiddle demonstrating how it's supposed to work (I don't think JSFiddle itself works in IE7 though, actually it kind of does, see this).
Update: Actually, lodash itself doesn't pass tests under IE7. Never mind that, the lodash.compat build does. However the compat build still has the same problem.
Does anyone have any ideas how to get this working under IE7? Has someone already solved this problem already?
Based on your fiddle, it looks like you are looking for the form widgets that are children of a widget.
dojox/form/Manager has a method called inspectFormWidgets that will do what you are lookiing for.
dijit/form/FormMixin has a method that you can reuse:
_getDescendantFormWidgets: function(/*dijit/_WidgetBase[]?*/ children){
var res = [];
array.forEach(children || this.getChildren(), function(child){
if("value" in child){
res.push(child);
}else{
res = res.concat(this._getDescendantFormWidgets(child.getChildren()));
}
}, this);
return res;
},
You can call it using the following
require(['dijit/form/_FormMixin'], function(DijitFormMixin) {
var widget = ...
var descendants = DijitFormMixin.prototype._getDescendantFormWidgets.call(
widget, widget.getChildren());
});
If you need to get more than just form widgets you can create a function that is similar to the _getDescendantFormWidgets.

Firebreath Object in AngularJS

I have tried to include a FireBreath plugin object in an AngularJS view, however when I try to render the view I get this error:
TypeError: Cannot read property 'nodeName' of undefined
I am able to successfully include the object in the view with $compile like this:
$("body").append($compile('<object id="plugin" type="application/x-firebreathplugin" width="0" height="0></object>')($scope));
However, after including the object like this I cannot get my plugin to fire an event in the JS.
Doing something like this:
plugin = document.getElementById('plugin');
console.log(plugin);
Returns
TypeError
In the Chrome console. But I can still do:
plugin.callFunction();
And have a FireBreath method execute. The issue is when I try to get an event to fire in the JS. No matter what I try, I cannot get the event to fire. So this code will never execute:
var addEvent = function(obj, name, func) {
obj.addEventListener(name, func, false);
}
addEvent(document.getElementById('plugin'), 'firebreathEvent', function(data) {
console.log('data ' + data);
});
var plugin = document.getElementById('plugin');
plugin.functionThatTriggersFireBreathEvent();
Does anybody know if it has something to do with accessing the object after calling $compile? I noticed that in regular HTML (before using AngularJS) logging the plugin in the console returns this :
<JSAPI-Auto Javascript Object>
So I am thinking that whatever I am getting with document.getElementById after using $compile is not the same.
What would be easier is is if I could just include the <object> tag in the view.html file and have it display in <body class='ng-view'> but I get the top TypeError, so if anyone has any ideas for that, that would be preferred.
Any help is appreciated. Thanks.
If anyone is interested, because I could not get the event to fire, I followed along to this link:
http://colonelpanic.net/2010/12/firebreath-tips-asynchronous-javascript-calls/
(which I think is your blog #taxilian) to get the data back to the JS.
Plugin Code: Great example in the link.
JS Code:
//attach FireBreath Object to AngularJS View
$("body").append($compile('<object id="plugin" type="application/x-firebreathplugin" width="1" height="1"><param name="onload" value="pluginLoaded"/></object>')($scope));
var callback = function(data) {
//data is an object
console.log(data.resultFromFireBreath);
}
plugin = document.getElementById("plugin");
plugin.getData(callback);
This will have to work for now until someone can figure out how to attach an event to the plugin object after $compile.
I ran into the same problem and was able to make the problem go away by creating a read-only nodeName property in my plugin object. I asked about this in a firebreath forum post and taxilian suggested adding this to JSAPIAuto.cpp, which also worked, so I submitted a pull request with the change.
I once spent about 6 hours trying to make FireBreath plugins work with jquery; it was really educational, but ultimately I determined that it wasn't worth the work.
Long story short is that it's not worth it; particularly since even if you could make it work, it would break on IE9 where FireBreath doesn't support addEventListener (IE never gives it the even info, so it's a little hard to support) and you would need to use attachEvent anyway.

use of globalstorage is deprecated. please use localstorage instead

I got this message when doing some javascript programming, and after some google searches, I have no idea what it means, or how i cause this error. I'm including the code below, can someone explain it to me or point me to a resource on how to fix it or what is happening at all? The weird thing is that I have other code just like this part in my program, and it never gives me errors about them, so i'm really confused. Also, I only get this error to display with firebug running, else wise it just doesn't work and no error message is displayed. I also tried it in Chrome, and had the same issues, no error message but the code doesn't work.
foundTextFn = function(){
console.log('fire');
if (foundTextArrayPosition != foundTextArray.length){
writeText(foundTextArray[foundTextArrayPosition],"happy");
foundTextArrayPosition += 1;
}
foundTextFnTimer=setTimeout("foundTextFn()",4000);
}
Here is another of my methods, it is basically the same thing, but it works fine. And if it matters, all of these variables are global variables declared at the start of my file as var foundTextArrayPosition = 0; for example.
awayFn = function(){
if (awayArrayPosition != awayArray.length){
if (changeAwayState){
changeAwayState = false;
writeText(awayArray[awayArrayPosition],"normal");
awayArrayPosition ++;
temp = pickRandomSpot();
randomX = temp[0];
randomY = temp[1];
}
else{
changeAwayState = true;
}
awayTimer=setTimeout("awayFn()",10000);
}
else{
abandoned = true;
whyGoneArrayPosition = 0;
whyGoneFn();
}
}
This is a deprecation error in Firefox 9. globalstorage was a way to store data in Firefox, but HTML5 introduced localstorage, which is now the preferred way (using window.localStorage).
https://developer.mozilla.org/en/DOM/Storage has more information.
I got the same error message and found a solution and perhaps the underlying cause of conflict, I was using the jQuery validate function in the jzaefferer.github.com/jquery-validation/jquery.validate.js library along with jQuery 1.7.1
The problem:
I used $(document).ready with two different contexts. One with the noConflict wrapper and one without. By keeping both the same, the error message went away. Hooray!
The wrapper:
jQuery.noConflict();
jQuery(function($) {
$(function() {
$(document).ready(function() { ...}
});
});
See also this post on my blog.
Probably not related to the issue above but I will put it here for the search engines.
I got the same error message while doing some simple jQuery:
Use of globalStorage is deprecated. Please use localStorage instead.
[Break On This Error]
$(document).ready(function() {
It was however due to forgetting to actually include the link href to the jQuery.js file...!

Watch for a property creation event?

I need to be able to determine when an object is created (not a DOM element -- a JavaScript object).
An answer to this question has some very useful looking code for creating observable properties, so you can have a function fire when a property changes.
In my situation I need to do something when the object/property is created, not an existing property changed, and my limited understanding of such matters did not help me figure out if or how I could use that code to do this after much squinting.
The situation is: page loads a bunch of scripts. Some of the scripts create things that are needed by other scripts, e.g:
ThisStuff = (function () {
// blah blah
return self;
} ());
Some other code needs to initialize this ThisStuff, whenever it's available, which may be after the DOM is done loading. The user doesn't actually need ThisStuff right away, so it's fine for it to happen whenever the script is done loading. So I would like to do something along lines of:
$(document).ready(function() {
wheneverIsAvailable(window,'ThisStuff', function(object) {
object.init(args);
})
});
I realize there are other solutions to this problem (changing script order, or loading scripts on demand) but those are difficult because of the architecture. So I'm only interested in a way to do this versus other solutions. If jQuery offers some such functionality, that's fine also as I'm using it.
You could have a setInterval checking a number of times a second to watch the specific variable. You can check whether it is created using obj.hasOwnProperty(prop). When it is created, you invoke the function, and clear the interval.
It might be dirty but it might also just work fine for you.
Edit: I coded this for you: http://jsfiddle.net/jhXJ2/2/. It also supports passing additional arguments to the function.
window.__intervals = [];
function wheneverIsAvailable(obj, prop, func) {
var id = (Math.random()+"").substring(2);
var args = arguments;
window.__intervals[id] = window.setInterval(function() {
if(obj.hasOwnProperty(prop)) {
window.clearInterval(window.__intervals[id]);
func(Array.prototype.slice.call(args, 3));
// Call function with additional parameters passed
// after func (from index 3 and on)
}
}, 1000/ 50);
}
wheneverIsAvailable(window, 'test', function() {
alert(arguments[0]);
}, 'Woot!');
window.setTimeout('window.test = 123', 1000);
This is a bit far-fetched but it might work.
You would need to use knockoutjs, a javascript library. It's awesome but is built for a slightly different purpose.
Anyways it has a dependentObservable thing which allows to fire up an event whenever a certain value changes. Now I know you want on creation but you can check whether your variable holds any value (other than what you provided initially), if yes then consider it initialize.
Let me know if you think this sounds feasible.

Categories