I want to:
- instantiate a JavaScript array of objects, where objects properties refer to other properties of the object itself, and then
- use the array to configure click event of a set of buttons.
problems (pls see snippet above):
- mymessage and myvalue parameters are undefined when anotherfunction() is called
- when a button of class
myclass*
is clicked x[i].myaction(); is undefined because at the time the button is clicked, i evaluates 2
var x = [{
mymessage: "this is message1",
myclass: "myclass1",
myvalue: 10,
myaction: function() {
var res = anotherfunction(mymessage, myvalue);
//do something with res
}
}, {
mymessage: "this is message2",
myclass: "myclass2",
myvalue: 20,
myaction: function() {
res = anotherfunction(mymessage, myvalue);
//do something else with res
}
}];
function anotherfunction(m, v) {
alert(m);
return v;
}
for (var i = 0, len = x.length; i < len; i++) {
$('.' + x[i].myclass).click(function() {
alert(i);
x[i].myaction();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myclass1">Click me1</div>
<div class="myclass2">Click me2</div>