I might just be being a bit dim here, or it might be my relative weakness with javascript, but I'm kinda stuck.
I have a justgage dial, showing number of people checked in an office, out of a total number.
I have a setInterval call just after the gauge is initiallised. But I want to update BOTH the number present, AND the total number, because both might potentially change. I can get the numbers via an ajax call to my own api - but because the ajax call is asynchronous, if I use
setInterval (g.refresh(myfunc()), 1000)
how do I get multiple returns out of myfunc.
Alternatively, if I do
setInterval( myfunc(g), 1000)
function myfunc(g){
var foo=g;
$.ajax(blah)
.done(function(json){
// no g here
})
I have no reference to g on successful ajax call. (Though it is visible at var foo=g)
How do I get around this (multiple returns, or visible object)
Maybe there is a better solution but try to create the foo var as global and then you can use this in all the places you want.
Related
So, all of the code works quite well. A database a queried, the node/parent IDs are lazily passed to jsTree, and, if one types a term into the search bar—a similar process goes on, but the nodes passed to jsTree are those returned by another SQL query (using something like SELECT nodeID FROM table WHERE name LIKE %searchTerm%).
There's only one problem:
If I type too quickly into the search bar, the results get all mixed up with one another. If I type slowly (I'd estimate 2 letters a second max), everything works well. Any faster and everything is blurred together. (That is, if I'm searching for names which contain the term "test", and type this quickly, I'll get names that contain "t", "te", "tes", and "test" instead of just names that contain "test".)
Anyone have this problem before? Is there some "wait until ready" function I should be using?
I can suggest you to do the 'Timeout' workaround. Basically, you create a SetTimeout function with a delay of 200-400 miliseconds and launch your lazyload ajax there. Every inputbox.change event restarts the time. See example in pseudo-javascript:
$('#your-input').keydown(function(){
if(ajaxTimer != undefined) {
clearTimeout(ajaxTimer);
}
ajaxTimer = setTimeout(function(){
$.ajax({...}).done(function() {...}
},400);
})
Use a throttle on the typing input, basically guarantees that a function will be called a maxmimum of once every X seconds. Sure you could write your own however there is a great library out there already.
check it out if you're interested http://benalman.com/projects/jquery-throttle-debounce-plugin/
I have an interesting issue - when I perform an AJAX call that refreshes this Appointment List dropdown with new entries based on either page load or a filter that is entered - the .val() method will not set
This is what success of the AJAX method will do - basically it sets back up the AppointmentList dropdown with new entries:
$.map(data, function (item) {
$('#AppointmentList').get(0).options[$('#AppointmentList').get(0).options.length] = new Option(item.AppointmentTime, item.ID);
});
This is what calls the function which basically just contains the $.ajax() method that re-populates the #AppointmentList dropdown. When I get the new set of values back - I still need it to have the old "appointment" pre-populated.
var tempVal = $('#AppointmentList').val();
DropDownList();
$('#AppointmentList').val(tempVal);
This does nothing, and the first element in the list re-created is selected.
However if I put a breakpoint on :
$('#AppointmentList').val(tempVal);
Then it seems enough time has passed for this dropdown to be able to be changed - if there is a breakpoint and I continue - the dropdown will change back to the value I want it to be if I am debugging the Javascript.
Any ideas on how to refactor this? I've been thinking maybe when we actually do the $.map() function we can set our old value up there - but this code seems to work... should I have a bit more time between when the Ajax finishes and I need to set the .val() again.
Ask a dumb question - figure out a dumb answer - I guess. Asynchronous. Duh.
Move those two lines to where this one is above the $.ajax() call:
var tempVal = $('#AppointmentList').val();
Then, put the line that sets the value within the success, but after the $.map():
$('#AppointmentList').val(tempVal);
I am using async.js to work on an array that holds roughly 12'000 values. The problem I'm currently facing is that I am not 100% certain what I can take for granted from async.js. First let me show you an abstract of the iterator function im using (coffeescript):
baseFace = 0
dataBuffer = new DataBuffer() # my own class that wraps DataView on an Uint8Array
async.each(#blocks,
(block, callback) =>
numFaces = writeToBuffer(dataBuffer, block, baseFace)
baseFace += numFaces
callback(null)
,
() =>
console.log 'done'
)
So essentially the order in which the blocks are written to the buffers is unimportant, but there are two things I need to be assured of:
The entire writeToBuffer has to be done atomic, its not reentrant since it writes to the end of the given buffer and the block has to be written as one (multiple calls to DataView.setXXXX)
The baseFace variable too must be accessed atomically inside the function. it cant be that writeToBuffer is called for another element before the face count of the previous call to writeToBuffer has been added to baseFace
Basically you can say my iterator cannot be evaluated multiple times at the same time, not even with interleaving (like, writeToBuffer, writeToBuffer, baseFace += numFaces, baseFace += numFaces). Coming from C++/C# etc I always fear that something goes wrong when methods access data like in the above example.
Thank you for any insight or tips about that topic, Cromon
I know that node.js is asynchronous, but what I don't really understand is how much.
Example:
If a need to do 3 things in sequence, and I need every thing is done before the other begins, Do i must need to use Callback?
var myContainer;
for(var i=0;i<10000;i++)
myContainer.push(i.toString());
for(var j=0;j<myContainer.length;j++)
console.log(myContainer[j]);
for(var x=0;x<myContainer.length;x++)
myModuleForEmails.sendEmailsTo(myContainer[x]);
Ok, suppose for one moment I have a module like Imap ready and calling myModuleForEmails.sendEmailsTo(myContainer[x]) I really send the email.
I know also that this program is absolutely useless, but it's just to understand.
Suppose I must push all 10000 string in myContainer, only THEN log all the string that are in myContainer in the console, and only AFTER BOTH I need to send the emails.
Is this version reliable or do I need 2 callback? And Does the number of iteration I do matter? i.e, if i had used 10 instead of 10000, could I have used this syntax because it takes so few to do 10 operation that finishes the first for cycle before starting the second?
With some help from StackOverflow community I was able to get my dirty flag implementation to work, based on this example: http://www.knockmeout.net/2011/05/creating-smart-dirty-flag-in-knockoutjs.html
It does exactly what I want, except for a single use case that I don't know how to solve.
Basically I have a select menu that gets automatically populated from the database. This select menu also has an option to make an Ajax call to my back end and have the list of options refreshed, database updated and return the result. This is where things get hairy for me.
First method works fine, however, it has to re-index and re-apply my entire viewModel and takes about 2-3 seconds, running on a local machine with 16gigs of ram and SSD.
jsondata.component.available_tags = result.available_tags;
ko.mapping.fromJS(jsondata, viewModel);
Second method also works, and pretty much instantaneous, however, it sets of isDirty() flag, which I would like to avoid, because this data is already coming from the database and I wont need to save it. I can not use isDirty.reset() method either, because if isDirty was set by something else before I clicked an menu option to update available_tags, it will reset that too. Which I would also like to avoid.
viewModel().component.available_tags(result.available_tags);
My question is: With the first method, can I force UI refresh with ko.mapping.fromJS() on a particular element and not entire dataset? Or, with a second method, can I avoid setting isDirty flag set when available_tags are updated? The twist is that I still need to keep available_tags as an observable, so the select menu is automatically generate/updated.
UPDATE: I was able to update mapping for that one single element with
ko.mapping.fromJS(result.available_tags, {}, viewModel().component.available_tags);
but that immediately set off isDirty flag... Argh
In addition to Tomalak's suggestions, which I totally agree with, maybe the toJSON method can help you out in similar cases where you don't want to split the model. If your dirty flag implementation uses ko.toJSON as a hash function, as Ryan Niemeyer's does, you can give your model (on which the dirty flag is active) a toJSON method, where you do something like this:
function MyObjectConstructor() {
this.someProperty = ko.observable();
this.somePropertyNotUsedInDirtyFlag = ko.observable();
}
MyObjectConstructor.prototype.toJSON = function () {
var result = ko.toJS(this);
delete result.somePropertyNotUsedInDirtyFlag;
return result;
};
Please be aware that this is also used to serialize the object in some other occassions, such as ajax calls. It's generally a handy function for removing computeds and such from your objects before using them in a different context.