explain javascript: value assignment fails - javascript

var sc = new stuCore();
function stuCore() {
this.readyPages = [];
this.once = true;
var self = this;
// gets called asynchronously
this.doPrepPage = function (page){
if(self.once == true){
// still gets executed every time, assignment fails
self.once = false;
doSomeStuffOnce();
}
};
this.addReadyPage = function (pageid) {
console.log("readypage called");
this.readyPages.push(pageid);
if (!$.inArray(pageid, self.readyPages) != -1) {
this.doPrepPage(pageid);
}
};
}
why does this assignment fail? I thought I knew the basics of js, but I'm stumped by this. And furthermore what would be a possible solution? call a constructor first and set the variable there?
EDIT:
gets called like this in some other script:
sc.addReadyPage(self.id);

The jQuery.inArray function will return the index in the containing array for the given value. Your script pushes pageid into this.readyPages before checking whether it exists in self.readyPages. this.readyPages and self.readyPages are the same array reference, so the result will always be zero or greater, so the condition that calls doPrepPage will never run.
You could try switching their order around:
this.addReadyPage = function (pageid) {
console.log("readypage called");
if ($.inArray(pageid, self.readyPages) != -1) {
this.readyPages.push(pageid);
this.doPrepPage(pageid);
}
};
(edit: Removed the additional !, thanks #chumkiu)

If I understand correctly you're calling this.doPrepPage as <insert variable name here>.doPrepPage?
If this is the case then your var self passes through to the anonymous function and is stored there, so everytime you call this.doPrepPage it takes the local variable of self.
Try setting self to a global variable, this way it will permanently modify self so each time this.doPrepPage is called it uses the updated variable.

Related

Returning a value inside an if clause in javascript

_editor: function () {
//retrieve all the editors on the current page
var editors = window.tinymce.editors;
var container = this.element;
//pick one that's associated with current container
$(editors).each(function (i, ed) {
if (ed.id == container.id) {
return ed; // even if this is invoked,
}
});
// undefined is returned
}
I had to change the above code to
_editor: function () {
//retrieve all the editors on the current page
var editors = window.tinymce.editors;
var container = this.element;
var editor;
$(editors).each(function (i, ed) {
if (ed.id == container.id) {
editor = ed; // do not return yet. Store it.
}
});
return editor; // return here
}
I assume this is because of JavaScript's scope characteristics. Could someone explain 1) if this is only inherent in JavaScript 2) what exactly is going on in each functional scope in the above code?
Thank you.
In the first case, you are returning a value from that anonymous function passed to $(editors).each, not the outer function. In the second case you are returning from the outer function.
This is how it works with pretty much any language that allows nested functions. return only returns from the innermost function.
The issue is that you have nested functions. You have the function assigned to the _editor property, and within that you have a function that's being invoked by $.each(). The return statement returns from the closest containing function, so in the first example it's returning from the $.each() iteration function, not the _editor function.
$.each() uses the return value of the iteration function to determine whether to continue looping -- if the function returns false, it stops at that element (similar to using the break; statement in a for or while loop).
Could someone explain 1) if this is only inherent in JavaScript 2) what exactly is going on in each functional scope in the above code?
The code is returning from the function passed to .each(), so it doesn't impact the enclosing function.
You can use $.grep for a cleaner solution.
_editor: function () {
//retrieve all the editors on the current page
var editors = window.tinymce.editors;
var container = this.element;
return $.grep(editors, function (ed, i) {
return ed.id == container.id;
})[0];
}
This is basically a filter. The result will be the items in the collection where you returned a truthy value. And so we just return the first truthy result (index 0 of the result).
It returns from the function called by each:
$(editors).each(function (i, ed) { // <---
if (ed.id == container.id) { |
return ed; // <--- this exits this --
is [this] only inherent in JavaScript[?]
No, many languages which use anonymous functions, also called lambdas, operate like this. A couple of examples are C# and ruby. Calling return exits themselves, rather than the functions they are invoked in.
what exactly is going on in each functional scope in the above code?
$(editors).each(function (i, ed) {
if (ed.id == container.id) {
editor = ed; // do not return yet. Store it.
}
});
The function body is called once for each element ed in $(editors). When the loop exits, the last value for which ed.id == container.id is then stored in editor. The second argument i is the index (0,1,2,3,...) incremented in each iteration.

Calling nested function from nested setInterval in an Object Namespace environment

I have this following piece of code:
var stats = {
....,
checkExistance :
function(url){
var newUrl = url.substring(0, url.lastIndexOf("/")) + "/asyncCheckChartExistance";
var xhrObj = stats.getXhr();
var poolInterval = setInterval("poll()", 100);
function poll(){
xhrObj.open("GET", newUrl, true);
xhrObj.send(null);
xhrObj.onreadystatechange = function(){
if(xhrObj.readyState === 4 && xhrObj.status === 200){
if (xhrObj.responseText.length === true){
console.log("Exists!");
clearInterval(poolInterval);
} else {
console.log("Not Yet!");
}
}
}
}
},
}
I created the stats namespace. In this namespace I'm trying to create a function which polls the server every second. I should access this function this way: stats.checkExistance(myUrl).
However it seems that the setInterval function is not able to see the poll() function. I know that this is normal behavior taking in consideration that these are nested inside another function.
If I were to write this in the Global namespace there would be no problem but I'm interested to make this work in this kind of namespace. Any ideas? Thanks!
when you pass a string to setInterval, it runs in the global scope, by default, where poll would not be defined since it only exists in the scope of the checkExistance function.
To fix the issue, pass an anonymous function to setInterval instead:
var poolInterval = setInterval(function () {
poll();
}, 100);
Passing an anonymous function is usually the best idea as it allows you to write any javascript expressions/statements for the interval instead of just calling one function.
When you pass a string to setInterval, that string is interpreted as global code, and since poll is not a global function, a reference error is thrown.
However, you can pass a function reference instead of a string, and since the poll function is available in the scope in which the setInterval invocation is made, you can just write this:
var poolInterval = setInterval( poll, 100 );
var stat = {
say: function(name){
function doit(){
console.log(name);
}
setInterval(doit, 1000);
}
};
stat.say("hi");​​​​​​​​​​​
A simple demo to show how. You will see "hi" every second.

Reassign variables stored in closure using a callback or global function

EDIT
Let me get more to the point. I'm trying to create a psuedo promise implementation. The idea here being that I have a callback that won't be executed until an asynchronous call is received. So I'm simply queueing up all the calls to this function until the time at which it's notified that it can be executed. The queue is emptied and any further call to the function is SUPPOSED to execute immediately, but for some reason, the function is still queueing. This is because, for whatever reason, my redefinition of the runner function is not working correctly. The code below was my sleep deprived, frustrated version of every thought that went through my head. Here's the actual code:
function Promise(callback){
var queue = []
, callback = callback
, runner = function(){
queue.push({
context: this,
args: Array.prototype.slice.call(arguments, 0)
});
}
;//var
runner.exec = function(){
for(var i = 0, ilen = queue.length; i < ilen; i++){
var q = queue[i];
callback.apply(q.context, q.args);
}
runner = callback;
};
return runner;
}
test = Promise(function(){
$('<div/>').appendTo('#output').html(Array.prototype.slice.call(arguments,0).toString());
});
test(1,2);
test(3,4);
test.exec();
test(5,6);​
http://jsfiddle.net/a7gaR/
I'm banging my head against the wall with this one. I'm trying to reassign variables in a function from a call outside the function itself (ideally by passing a reassignment function as a callback). In the example I posted on jsfiddle, I made a global function that, in theory, has a reference to the variables contained within its parent function. Upon calling that external function, I expect it to reassign the values that the other function is using. It doesn't seem to work this way.
window.test = function temp() {
var val = 7,
func = function() {
return val;
};
window.change = function() {
window.test.val = 555555;
$('<div>Changing ' + val + ' to ' + window.test.val +
'</div>').appendTo($output);
val = window.test.val;
temp.val = window.test.val;
func = function() {
return 'Why isn\'t this working?';
}
}
return func();
}
var $output = $('#output');
$('<div/>').appendTo($output).html('::' + test() + '::');
window.change();
$('<div/>').appendTo($output).html('::' + test() + '::');
http://jsfiddle.net/YhyMK/
The second time you call test you're creating a new local variable called func and defining a new window.change that closes over that new variable. The changes you made to the original func by calling the original window.change are not relevant in the second call.
Also note that the following line:
window.test.val = 555555;
...does not modify/refer to the val variable in the outer function. window.test.val refers to a property named val on the test object (which happens to be a function), not any local variable.
You are trying to refer to a local variable in a function with the syntax func.varname. That won't work, that's not the way local variables work.
I finally created a function that would perform this operation. The gist for it is here: https://gist.github.com/2586972.
It works like this...
You make a call to Defer passing the callback whose functionality you'd like to delay:
var deferredCB = Defer(function(){ console.log(this,arguments) };
deferredCB will now store all of the arguments you pass allowing them to be executed at some later date:
defferedCB(1);
defferedCB(2);
Now, when you're ready to perform the operation, you simply "execute" deferredCB:
defferedCB.exec();
Which results in:
// window, 1
// window, 2
All future calls to deferredCB will be executed immediately. And now that I'm thinking about it, I'll probably do a rewrite to allow you to reset deferredCB to it's pre-executed state (storing all the arguments again).
The key to making it work was having a wrapper function. Javascript simply won't let you reassign a function while it's being executed.
TADA!!!

Variable Undefined in Anonymous Function

function updateServerList() {
var i;
for (i=0; i < servers.length; i++) {
var server = servers[i];
var ip = server['serverIp']
var html = constructServer(i);
var divId = '#server' + ip.replace(new RegExp("\\.", "mg"), "-");
var visible = $(divId).find(".server_body").is(":visible");
var div = $(divId);
div.html(html);
// Set div class.
var prevState = div.attr('class').substring(7)
if (prevState != server['state']) {
if (server['state'] == 'ok') {
console.debug(server);
div.slideUp('fast', function(server) {
$(this).removeClass();
$(this).addClass('server_ok');
var id = ipToId[server['serverIp']];
console.debug(id);
if (id == 0) {
adjacentIp = servers[1]['serverIp'];
adjacentDivId = '#server' + adjacentIp.replace(new RegExp('\\.', 'g'), '-');
$(adjacentDivId).before(this);
}
}).delay(1000);
div.slideDown();
}
}
}
console.debug shows server as being defined, but inside the anonymous function, server is not defined. What am I going wrong?
because server is an argument to the function, its masking the value of the server at the higher level. You need to either pass server to the function, or remove the function argument. I would do the latter, as slideUp doesn't give you a way to pass arguments. You could do it but its needlessly complicated; it would look something like the following
div.slideUp('fast', (function(server) {
return function(){
// your stuff here, server is now 'closed in', i.e. in a closure
}
})(server)); // <-- this server is the current value in the loop
what you are doing here is invoking a new function right away, passing in the argument server, and returning a new function that receives that value.
var server = servers[i];
var prevState = div.attr('class').substring(7);
if (prevState != server['state']) {
if (server['state'] == 'ok') {
console.debug(server);
div.slideUp('fast', function() {
...
var id = ipToId[server['serverIp']];
}
}
Inside your anonymous function, "server" is still within the function scope. No need to pass it in as an argument.
The Quick Fix
// ...
div.slideUp('fast', function() { // `server` argument removed
// ...
});
The Explanation
There is no need to pass server to the function. The anonymous function "closes" over the server variable.
This is merely a function declaration:
function (server) {...}
You aren't passing anything to the function yet, as it isn't being invoked yet! The (server) bit
in a function declaration simply lets you name the arguments to your function. Only when you invoke the function can you pass arguments:
var name = "Jill";
var showName = function (name) {
alert(name);
};
showName("Jack"); // alert box shows "Jack"
showName(); // alert box shows "undefined"
So, when you declare that the name of the first argument to your anonymous function is server, there is a name conflict which prevents the original from being accessible; the server in your anonymous function is whatever slideUp passes as the first argument, which, according to the documentation, is nothing, so server is now undefined.
If this is confusing (and I suspect it is), I would suggest reading about javascript closures. Here's a good place to get started.
Fun fact: you can actually access arguments, in order, without having any explicit names, by using Javascript's built in arguments array object inside a function:
var sum = function () {
var i, total = 0;
for(i = 0; i < arguments.length; ++i) {
total = total + arguments[i];
}
return total ;
};
alert(sum(1,2,3)); // Displays "6"
alert(sum(1,2,3,4)); // Displays "10"
alert(sum(1,0,2,3)); // Displays "6"
alert(sum()); // Displays "0"

Possible to stop a Javascript function with another Javascript call?

I am having a problem where I want to stop a particular function from executing. This function is located on another plugin which I can't change the core files so I am wondering if I can stop a specific function from that file from executing?
So for example that function is testFunction(); and I want to stop that later in the code maybe in on document ready...etc.
Thanks!
Is the function public (as opposed to private via a closure)? And, does it need to be operational at all for things to work, or can you chop it out in total and be fine? If the latter, you can replace the function with a new one:
otherLibrary.testFunction = function(){};
If you want to disable it for a temporary amount of time, you can store the function in a temporary variable, and restore it later:
var removedFunc = otherLibrary.testFunction;
otherLibrary.testFunction = function(){};
// do something, time passes, whatever...
otherLibrary.testFunction = removedFunc;
Or, if you want to be able to toggle it, a slight variation:
var removedFunc = otherLibrary.testFunction;
var testFunctionEnabled = true;
otherLibrary.textFunction = function(){
if(testFunctionEnabled){
removedFunc.call(this, arguments);
}
};
And then just set testFunctionEnabled as you need to.
you should try to extend the function before you call it e.g.
$.extend(plugin.function, myNewFunction);
also, check the plugin API to see if you can pass a paramter to override the function or actually access the api of the plugin e.g.
$('#mytip').api('hover', myHoverFunction);
If you have access to the object which refers to the "testFunction" function then you could replace it with an empty function, e.g.:
SomePlugin.testFunction = function() { };
Ultimately, if you don't have a way to overwrite that symbol then there's not much you can do to stop the method from running (unless you can provide more details).
If that function schedules itself with setInterval, you can use clearInterval(thefunction) to prevent it from being called again. But if it's a loop, I don't know if that's possible.
Simply set the function to null.
JavaScript example:
function write() {
el.innerHTML += 'Lorem ipsum dolor sit amet.<br />';
if (execute != null) execute();
}
function execute() {
setTimeout(function() { write() }, 500);
}
function abort() {
execute = null;
}
window.onload = function() {
el = document.getElementById('blah');
execute();
}
HTML:
<button type="button" onclick="abort()">Abort</button>
<p id="blah"></p>
Also you can change the following to implement stop/start. For this, assign the execute function to a variable so that you can later assign that variable back to execute.
var oldfunc = execute;
function abort() {
if (execute == null) {
execute = oldfunc;
execute();
} else {
execute = null;
}
alert(execute);//shows the function code
}
You can overwite any method you have access to- but if the code in your module calls it internally you better give it an appropriate return.
document.write=function(){return true};
alert(document.write('tell me more!'))

Categories