遇到程序流问题 - 在AJAX回调和渲染PIXI JS之间徘徊

时间:2015-04-08 19:07:15

标签: javascript ajax

我无法顺利完成js脚本流程。这是一个接收和发送鼠标坐标并绘制它们的脚本。

这是:

//Initialize PIXI
var stage = new PIXI.Stage(0x000000);
var renderer = new PIXI.WebGLRenderer(1600, 900);
document.body.appendChild(renderer.view);

//requestAnimFrame(animate);
function animate() {
    console.log("Draw.");
    requestAnimFrame(animate);
    renderer.render(stage);
}

//Function for receiving data.
indx = 0;
var makeRequest = function(){
   var ajaxFunction = function(){
      if(ajaxRequest.readyState == 4){
        var pointsStr = ajaxRequest.responseText.split("C"); //The co-ordinates are received in this form: "pointCpointCpointCpoint...pointCindex"
        indx = parseInt(pointsStr[pointsStr.length - 1]);
        for (i = 0; i < pointsStr.length - 1; i++) {
            if(pointsStr[i] != ""){
                var points = pointsStr[i].split(",");
                mouseX = parseInt(points[0]);
                mouseY = parseInt(points[1]);

                var graphics = new PIXI.Graphics(); //Why create new graphics every time? PixiJS bugs out if I don't. Probably also something to do with the flow.
                graphics.lineStyle(1, 0xFFFFFF);
                stage.addChild(graphics);
                graphics.drawRect(mouseX,mouseY,1,1);
                renderer.render(stage);
                console.log("Received.")
            }
        }
      } 
   }
   var ajaxRequest = new XMLHttpRequest();
   ajaxRequest.onreadystatechange = ajaxFunction;
   ajaxRequest.open("GET", "http://127.0.0.1/receiveData/0=" + indx, true);
   ajaxRequest.send();
}

//Function for sending data.
var sendRequest = function(arr){
   var t = ""
   for (var i = 0; i < arr.length; i++) {
        t += arr[i].x.toString() + "," + arr[i].y.toString() + "C";
   }
   t = t.slice(0,-1);
   var ajaxRequest = new XMLHttpRequest();
   ajaxRequest.open("POST", "http://127.0.0.1/sendData/" + t, true);
   ajaxRequest.send();
   console.log("Send.")
}

pos = {
    x: 0,
    y: 0
}

var mouseRecording = new Array();

document.addEventListener('mousemove', function(e){ 
    var p = pos;
    p.x = e.clientX || e.pageX; 
    p.y = e.clientY || e.pageY;
    mouseRecording.push(pos);
    console.log("" + p.x + "," + p.y)
}, false);

var interval = setInterval(function(){
    console.log("Make Request.");
    sendRequest(mouseRecording);
    makeRequest();
}, 100);

基本上,问题是流程确实不一致。

例如,它只是POST和GET 10秒而没有回调运行,但随后突然有200个请求随后会运行,然后可能会在蓝色的月亮中呈现一次屏幕等等。

这里使程序充分流动的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

关于函数命名和职责的一些注意事项:1。如果你的函数有一个非常通用的短名称,并且在它上面有一个说明不同的注释,那么就去掉注释并重命名你的函数。 2.你的功能应该只做它所说的功能,仅此而已。 3.您的函数不应修改其父作用域。副作用使调试变得困难。

那就是说,让我们先把它分解成一大堆微小的功能,这些功能做得很少,他们可能做错了什么。并命名为他们不做任何其他事情。

//Initialize PIXI
var stage = new PIXI.Stage(0x000000);
var renderer = new PIXI.WebGLRenderer(1600, 900);
document.body.appendChild(renderer.view);

function httpRequest(method, url, success, fail) {
  var xmlhttp = new XMLHttpRequest();

  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 ) {
      if(xmlhttp.status == 200){
        success(xmlhttp.responseText);
      }
      else {
        fail();
      }
    }
  }

  xmlhttp.open(method, url, true);
  xmlhttp.send();
}

function getRequest(url, success, fail) {
  httpRequest('GET', url, success, fail);
}

function postRequest(url, success, fail) {
  httpRequest('POST', url, success, fail);
}

function buildDataStringFromCoords(coords) {
  return coords.map(function(coord) {
    return coord.x.toString() + ',' + coord.y.toString();
  }).join('C');
}

function buildCoordsFromDataString(dataString) {
  return dataString.split('C').map(function(coordString) {
    var points = coordString.split(',');
    return {x:+points[0], y:+points[1]};
  });
}

function renderCoords(coords) {
  var graphics = new PIXI.Graphics(); //Why create new graphics every time? PixiJS bugs out if I don't. Probably also something to do with the flow.
  graphics.lineStyle(1, 0xFFFFFF);
  stage.addChild(graphics);
  graphics.drawRect(coords.x, coords.y, 1, 1);
  renderer.render(stage);
}

function requestCoords(indx, success, fail) {
  var url = 'http://127.0.0.1/receiveData/0=' + indx;
  getRequest(
    url, 
    function(response) {
      var coords = buildCoordsFromDataString(response);
      success(coords);
    },
    function() {
      fail();
    }
  );
}

var sendCoords = function(coords, success, fail) {
  var url = 'http://127.0.0.1/sendData/' + buildDataStringFromCoords(coords);
  postRequest(
    url,
    function() {
      success();
    },
    function() {
      fail();
    }
  );
}

pos = {
  x: 0,
  y: 0
};

var mouseRecording = new Array();

document.addEventListener('mousemove', function(e){ 
  var p = pos;
  p.x = e.clientX || e.pageX; 
  p.y = e.clientY || e.pageY;
  mouseRecording.push(pos);
  console.log('Mouse moved', p.x, p.y);
}, false);

var interval = setInterval(function(){
  console.log("Make Request.");
  sendCoords(
    mouseRecording,
    function() {
      console.log('Successfully sent coords', mouseRecording);
    },
    function() {
      console.log('Failed to send coords', mouseRecording);
    }
  );
  requestCoords(
    indx,
    function(coords) {
      console.log('Successfully fetched coords', coords);
      coords.forEach(function(coord) {
        renderCoords(coord);
      });
      console.log('Rendered coords', indx);
    },
    function() {
      console.log('Failed to get coords', indx);
    }
  );
}, 100);

现在让我们编写一些测试来证明每个部分都是正确的#34;所以每次出现问题时你都不必逐步完成整个大事。例如:

function testBuildDataStringFromCoords() {
  return buildDataStringFromCoords([{x:123,y:456},{x:987,y:654}]) === '123,456C987,654';
}

这可能无法完全解决您遇到的问题,但我希望这会让您的生活更轻松,并使问题更加透明。