I’m trying to create a Object class that will take data and create a list of elements. I also want to attach a click event on the new LI’s that fires a method of the class. However, when using the
el.click(function() {
this.method();
});
this no-longer references the Class, so clicking on the li gives you an undefined method error. Suggestions on how to attach the class method to the newly create elements?
JS Code:
if (typeof Object.create !== 'function') {
Object.create = function(o) {
function F() {}
F.prototype = o;
return new F();
};
}
var base = {
init: function(data) {
this.data = data;
this.show_data();
},
show_data: function() {
for (i = 0; i < this.data.bindings.length; i++) {
var $item = $('<li>' + this.data.bindings[i].ircEvent + '</li>');
$item.click(function() {
this.show_clicked(i);
});
$('#it').append($item);
}
},
show_clicked: function(index) {
console.log('clicked in method');
}
};
var extended = {
show_alert: function() {
alert('second class');
}
};
var myObj = {
"bindings": [
{
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"},
{
"ircEvent": "PRIVMSG",
"method": "deleteURI",
"regex": "^delete.*"},
{
"ircEvent": "PRIVMSG",
"method": "randomURI",
"regex": "^random.*"}
]
};
$(document).ready(function() {
var baseObj = Object.create(base);
baseObj.init(myObj);
});
In order to make your method work in the click function, just reference your global variable that contains the object.
The line:
should be changed to:
If you want your index value to be displayed in the final result, you’ll have to either pass that as data, or use jquery to determine which index was clicked.
Here is an updated fiddle that works – http://jsfiddle.net/EwC3r/4/