How to pass parameters in function object literal
CalAlt
I would like to pass integers as min and max parameters to a function to return a random number to be used by another function. I am new to the Java language and am using the object literal pattern. Currently I get the error "this.randomGenerator is not a function". How can I return randomGenerator
the numbers used from it interaction
?
bindEvents: function() {
$('#left').on("click", this.interaction);
},
interaction: function() {
var selector = this.randomGenerator(0, 3);
var $columns = $('#left').find('div[col]');
$columns.children().removeClass('show');
$columns.eq(selector).children().addClass('show');
},
randomGenerator: function(min, max) {
var last,
value,
count = 0,
getR = function () { return Math.floor(Math.random() * (max - min)) + min; };
return function () {
var random;
if (count && value !== last) {
--count;
return last = value;
}
random = getR();
while (random === last) {
value = random;
++count;
random = getR();
}
return last = random;
};
},
Rory McCrossan
The problem is because this
in the click
handler you are referencing the clicked element, not the object containing the randomGenerator()
function .
To work around this, you can keep a reference to it in a variable before this
using $.proxy()
(or bind()
) setting it to the scope randomGenerator()
under which the function should run . Try this:
var obj = {
bindEvents: function() {
var _this = this;
$('#left').on("click", $.proxy(_this.interaction, _this));
// Note you can also use the native bind() method, if preferred:
// $('#left').on("click", _this.interaction.bind(_this));
},
interaction: function() {
var selector = this.randomGenerator(0, 3);
console.log(selector()); // just for testing...
var $columns = $('#left').find('div[col]');
$columns.children().removeClass('show');
$columns.eq(selector).children().addClass('show');
},
randomGenerator: function(min, max) {
var last,
value,
count = 0,
getR = function() {
return Math.floor(Math.random() * (max - min)) + min;
};
return function() {
var random;
if (count && value !== last) {
--count;
return last = value;
}
random = getR();
while (random === last) {
value = random;
++count;
random = getR();
}
return last = random;
};
}
}
obj.bindEvents();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="left">Click me</div>