I've searched all over the internet but couldn't solve the problem.
I am coding a game. Before the game starts, I prompt the user for difficulty, and user have to select a difficulty to start the game by clicking one of the buttons.
function GameManager(){
this.current = 0;
this.difficulty = 0;
this.toolbox = new Toolbox();
this.promptDifficulty(); // Here it should wait for user input
this.grid = new Grid(this.difficulty);
this.start();
}
GameManager.prototype.promptDifficulty = function() {
$("#difficulty").show();
this.toolbox.center();
var selected = false;
$('.selection').click(function(){
var $diff = $(this).attr('id');
if($diff === 'easy')
this.difficulty = 8;
else if($diff === 'medium')
this.difficulty = 9;
else if($diff === 'hard')
this.difficulty = 10;
$('#difficulty').hide();
});
};
However, it creates the Grid before the user selects the difficulty, and this messes up whole design. How can I make it wait until user clicks one of the difficulty settings?
1 Answer 1
The problem is the difficulty prompt is an async method, when you call the promptDifficulty() method, it shows the difficulty selector, but the rest of the script execution will continue before the user selects an item. So you need to use a callback to continue, which will be called once the user selects an item.
function GameManager() {
this.current = 0;
this.difficulty = 0;
this.toolbox = new Toolbox();
this.promptDifficulty($.proxy(function (difficulty) {
this.grid = new Grid(this.difficulty);
this.start();
}, this));
}
GameManager.prototype.promptDifficulty = function (callback) {
$("#difficulty").show();
this.toolbox.center();
var selected = false;
$('.selection').click($.proxy(function (e) {
var $diff = e.currentTarget.id;
if ($diff === 'easy') this.difficulty = 8;
else if ($diff === 'medium') this.difficulty = 9;
else if ($diff === 'hard') this.difficulty = 10;
$('#difficulty').hide();
callback(this.difficulty);
}, this));
};
Also Note the use of $.proxy(), because in the click handler this by default refers to the clicked element, so when you set this.difficulty it is not setting to the GameManager instance, you can solve by passing a custom execution context for the callback method.
Demo: Fiddle
3 Comments
this to $.proxy() - see the updateExplore related questions
See similar questions with these tags.