I stuck in a problem by coding on a javascript webapp with firebase:
function start() {
setInterval(getComps, 2000);
}
function getComps() {
permis=true;
for (var pc=policeNum; pc>0; pc--) {
policeRef.child(pc).once('value', function(snapshot) {
var oldData = snapshot.val();
//KI:
var compX=newX-oldData.X;
var compY=newY-oldData.Y;
updatePosition(compX, compY);
});
}
}
(The real code of the app is of course more complicated but this is enough to understand the problem I think) (The start() is called with a button in my index.html)
When I run my app I can see that updatePosition() is only called once in the beginning but not later again in my wanted interval. Do someone know what´s wrong here and can give me a example or explanation of a better code.
Thank you for every answer, I hope you can understand what I mean. (all variables are of course defined)
Related
Looking for some direction and help. I am new to JavaScript and NodeJS and have not been able to find anything online on how to do this. I've written a minesweeper game in JavaScript and would like to be able to inject user written code into the game loop instead of taking inputs.
The main problem I am running into is getting access to the methods I've built into the game class. Here's the code.
class Game {
constructor() {
this.GameBoard = new MineSweeperBoard(true);
autoBind(this);
}
pop(x ,y){
this.GameBoard.pop(x, y);
}
flag(x, y){
this.GameBoard.flag(x,y);
}
removeFlag(x,y){
this.GameBoard.RemoveFlag(x,y);
}
checkWin(){
this.GameBoard.CheckForWin();
}
getGameBoard(){
return this.GameBoard.GetRevealedGameBoard()
}
}
function StartGame() {
let CurrentGame = new Game();
let win = false;
while(CurrentGame.GameBoard.RunGame) {
//User Code here
*User written code should run right about here.*
// Check win condition
if(CurrentGame.checkWin()){
win = true;
}
}
Any help or direction would be appreciated.
*** Edit ***
To answer some question that have been asked.
1: This isn't secure: Yes I understand there are potential security implications to running user generated code. As of right now that is not a concern as this is mostly a proof of concept.
2: Why do I want to do this: Because I want to see if it's possible and I know others have found ways to securely run user code (i.e. Screeps). Right now I would like to see what is possible.
I have a feeling this is a simple issue I'm missing but after a couple of hours I've given up and decided to post in here.
I'm trying to implement a generic paging partial view that I can use across the entire site. As a result the paging model takes a function that will be bound to the paging controls that is used as a callback at a later time. See UpdateFunction below.
ViewModels.Shared._PaginationPartialViewModel pagination =
new ViewModels.Shared._PaginationPartialViewModel()
{
CurrentPage = Filter.Page,
ItemFrom = GenericHelpers.Paging_GetItemFrom(10, Filter.Page, TotalItems),
ItemTo = GenericHelpers.Paging_GetItemTo(10, Filter.Page, TotalItems),
TotalItems = TotalItems,
TableClass = Filter.Table,
TotalPages = (int)Math.Ceiling((double) TotalItems / 10),
UpdateFunction = "getTransfers('" + Filter.Table + "')"
};
Now when the model is bound to the view, this function is passed in as a callback to a javascript click event paginationClick() like so...
#Model.CurrentPage
The paginationClick() function fires, but when checking the dev console the callback method appears to be firing first. Here's the paginationClick() method... (I know that the page parameter is not currently being utilized btw!)
function paginationClick(control, page, callback)
{
if (!$(control).hasClass('stock-pagination__action_state_active')) {
$(control).parent().find('a').each(function () {
$(this).removeClass('stock-pagination__action_state_active');
});
$(control).addClass('stock-pagination__action_state_active');
callback;
}
}
I anyone can offer an extra pair of eyes it would be much appreciated!
I found a work around with this, instead of passing getTransfers in as a callback, I appended it to the control as a data-attribute then used eval to execute at the correct time like so:
data-callback="#Model.UpdateFunction"
and then
function paginationClick(control, page)
{
if (!$(control).hasClass('stock-pagination__action_state_active')) {
var arr_Controls = [];
$(control).parent().find('a').each(function () {
$(this).removeClass('stock-pagination__action_state_active');
arr_Controls.push($(this));
});
$(control).addClass('stock-pagination__action_state_active');
eval($(control).attr("data-callback"));
//callback;
}
}
It's not the solution I was after but it works. If anyone has any idea how to get it working as a callback please let me know.
I'm trying to use infinite-scroll to lazy load images. I'm getting the following error when it's called though:
TypeError: undefined is not a function
at handler (http://onfilm.us/ng-infinite-scroll.js:31:34)
Here's a very watered down look of what I have thus far.
function tagsController($scope) {
$scope.handleClick = function(tags) {
// Parse Tags
$scope.finished_tags = parsed_data;
};
$scope.$emit( 'handleEmit', { tags = $scope.finished_tags; });
};
function imagesController($scope,$http) {
var rows_per = 5;
$scope.$on('handleBroadcast', function(event, args) {
// Sort the images here, put them in matrix
// Example: matrix[row_number] = { picture1, picture2, picture3 }
$scope.data = matrix;
$scope.loadMore();
};
$scope.loadMore() = function() {
var last = $scope.images.length;
for ( var i = 0; i < rows_per; i++ ) {
$scope.images[last + i] = new Array();
$scope.images[last + i] = $scope.data[last + i].slice( 0 );
}
}
}
The rough idea is that the page loads the first time (w/ no tags) and get images from a PHP script. All of them. They are stored, and loadMore() is called which will populate $scope.images with 5 rows of images. It does, and they are loaded.
The line in that script is accessing $window.height and $window.scrollup. I'm still pretty green w/ Javascript, so feel free to lambast me if I'm doing something horribly wrong.
This is the broken version I'm testing with:
http://onfilm.us/test.html
Here is a version before the lazy loading was implemented, if seeing how the tags work will help. I don't think that's the issue here though.
http://onfilm.us/image_index.html
EDIT: I do think this is a problem w/ the ng-infinite-scroll.js script. The error is on line 31 (of version 1.0.0). It's telling me:
TypeError: undefined is not a function
It doesn't like $window apparently.
My JS Kung Fu is not really equipped to say why. YOu can see a literal copy/paste job from the simple demo here (with the error) onfilm.us/scroll2.html
By refering your site, It appears at first instance that your HTML-markup is not appropriate. You should move infinite-scroll to the parent of ng-repeat directive so that it will not make overlapping calls for each row generated. Please visit http://binarymuse.github.io/ngInfiniteScroll/demo_basic.html
I'm writing a simple Windows Gadget, but I can't seem to get the settings to save when using this functions. Here's some of the code that should get the task done, but still won't work:
var mySettings = new botanicallileo();
function botanicallileo()
{
this.kitID = "";
this.load = loadSettings;
this.save = saveSettings;
}
function saveSettings()
{
System.Gadget.Settings.writeString("test", "true");
System.Gadget.Settings.writeString("kitID", this.kitID);
}
function settingsClosing(event)
{
if (event.closeAction == event.Action.commit)
{
mySettings.save();
}
}
I must be missing something very important but I can't seem to find what it is. I know the settings aren't saving because I can check the .ini file, and nothing seems to pop up, while with other gadgets the new variables do appear and get saved in the file. Help will be appreciated.
Note: the settings "test" is just that, a test to see if anything was getting written at all. Needless to say it's not getting written.
I recently ran into a familiar javascript/jQuery timing bug and spent too long debugging it. What I need is a smarter debugging path for this problem.
In specific, my issue was that user inputs were supposed to be causing a Mongo database call and the results were sent, after a little math, to displayed outputs. But the displayed outputs were crazily wrong. However, once I added a FireBug break point the problem went away. At that point I knew I had a timing issue, but not how to solve it.
Here are the relavant pieces of code before the error:
handleDataCallBack : function(transport) {
var response = $.parseJSON(transport);
if(!hasErrors) { this.updatePage(response); }
},
accessDatabase : function(){
var params = { ... };
DAL.lookupDatabaseInfo(this.handleCallBackOutputPanel, this, params);
},
calculateValues: function() {
// some numerical values were updated on the page
}
onDomReady : function() {
// ...
//bind drop-down select change events
$('#someDropDown').change(function() {
me.accessDatabase();
me.calculateValues();
});
}
To fix the problem, all I had to do was move the "calculateValues" method from the onDomReady inside the call back:
handleDataCallBack : function(transport) {
var response = $.parseJSON(transport);
this.calculateValues();
if(!hasErrors) { this.updatePage(response); }
},
The problem was that the database hadn't responded before the calculations were started. Sure, that's easy to spot in retrospect. But what methods can I use to debug asynchronous timing issues in javascript/jQuery in the future? This seems well outside the context of IDE tools. And FireBug didn't help. Are there any tools for tracking down asynchronous web development issues? Or maybe some time-tested methods?
i assume your problem is caused here:
$('#someDropDown').change(function() {
me.accessDatabase();
me.calculateValues();
});
this issue is that your calculations are done just right after the call. seeing that the DB call is async, calculate does not wait for it. however, you can do it using "callbacks". i see you do try to implement it and yes, it is correct. however, i find this more elegant:
calculateValues: function() {
// some numerical values were updated on the page
},
//since this is your general callback hander
//you hand over the return data AND the callbackAfter
handleDataCallBack: function(transport, callbackAfter) {
var response = $.parseJSON(transport);
//you may need to use apply, im lost in scoping here
callbackAfter();
//or
callbackAfter.apply(scope);
if (!hasErrors) {
this.updatePage(response);
}
},
accessDatabase: function(callbackAfter) {
var params = {};
//pass callbackAfter to the function,
//after this is done, pass it to the handler
DAL.lookupDatabaseInfo(this.handleCallBackOutputPanel, this, params, callbackAfter);
},
onDomReady: function() {
$('#someDropDown').change(function() {
me.accessDatabase(function() {
//send over what you want done after.
//we'll call it "callbackAfter" for easy tracing
me.calculateValues();
});
});
}