[jQuery] Problem with bind parameters
I'm reading about how to bind function to events, I wrote an example,
but found a problem that I'm not sure how to resolve. The example is
simple, there is a button that instantiate Coso and bind click event
to a myFunc that log some data. Here is my example:
<code>
<script type='text/javascript'>
Coso = function(id) {
this.init(id);
}
Coso.prototype= {
init: function(id) {
this.btn = $("<button id='btn"+id+"'>boton "+id+" </button>");
this.id = this.btn.attr("id");
this.btn.bind("click", {id:this.id}, this.myFunc);
console.log( "init: "+ id);
},
myFunc: function(e, myParam) {
console.log(this.id);
console.log(e.data);
console.log(myParam);
},
addBtn: function(here){
this.btn.appendTo(here);
$(here).append("<br/>");
}
};
var t = 1;
function crearObj( )
{
var x= t++;
//nstantiate and append to #sandbox div
var c = new Coso( x );
c.addBtn("#sandbox");
}
$(function() {
$("#createObj").bind("click", crearObj);
// create three buttons.
$("#createObj").trigger('click');
$("#createObj").trigger('click');
$("#createObj").trigger('click');
});
</script>
<button id="createObj">Create button</button>
<div id="sandbox"></div>
</code>
The example works ok. You can create as much object as you want, and
every button show a message in the console, but not with the correct
data. When you click any of the button, it fire myFunc, and the output
is:
//example output for btn1
console.log(this.id); // outputs 1
console.log(e.data.id ); // outputs 3
console.log(myParam); // outputs undefined
the second line output 3 because there are 3 buttons. If i click
"create button" then the output become 4.
Any idea how can I fix this example to use paremeters inside myFunc,
either with e.data or myParam ??
Thanks
-- Gus