我怎么能等待socketIO事件的返回?

时间:2014-07-26 15:45:04

标签: javascript callback socket.io synchronous

我必须返回debugReturn事件的验证函数,但我不知道因为是异步的。我需要一种方法来返回true或false到validate函数。对不起我的英文:S

$('.num-pad').keyboard({
    layout: 'num',
    validate: function(keyboard, value, isClosing) {
        var data = $(keyboard['el']).attr('id').split('_');
        var var_index = data[data.length - 1];
        var var_name = data[0];
        for (var i = 1; i < data.length - 1; i++) {
            var_name += '_';
            var_name += data[i];
        }
        socket.emit('debugVar', {
            var_value: value,
            var_name: var_name ,
            var_index: var_index 
        });

        socket.on('debugReturn', function(msg) {
            if (msg == 1) {
                $('.ui-keyboard input').css('box-shadow', 'inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)');
                return true;
            } else {
                $('.ui-keyboard input').css('box-shadow', 'inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(255,0,0,.6)');
                return false;
            }

        });
    }
});

1 个答案:

答案 0 :(得分:0)

我解决了从验证功能外部处理键盘的问题

$('.num-pad').keyboard({
  layout: 'num',
  validate: function(keyboard, value, isClosing) {
      var data = $(keyboard['el']).attr('id').split('_');
      var var_index = data[data.length - 1];
      var var_name = data[0];
      for (var i = 1; i < data.length - 1; i++) {
          var_name += '_';
          var_name += data[i];
      }
      socket.emit('debugVar', {
        var_value: value,
        var_name: var_name ,
        var_index: var_index 
      });
      kb = keyboard;
  }
});

然后......

socket.on('debugReturn', function(msg) {
    if (msg == 1) {
        $('.ui-keyboard input').css('box-shadow', 'inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)');
        kb.options.validate = true;
        kb.accept();
        kb.options.validate: function(keyboard, value, isClosing) {
          var data = $(keyboard['el']).attr('id').split('_');
          var var_index = data[data.length - 1];
          var var_name = data[0];
          for (var i = 1; i < data.length - 1; i++) {
              var_name += '_';
              var_name += data[i];
          }
          socket.emit('debugVar', {
            var_value: value,
            var_name: var_name ,
            var_index: var_index 
         });
         kb = keyboard;;
    } else {
        $('.ui-keyboard input').css('box-shadow', 'inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(255,0,0,.6)');
    }

});