0

I would like to attach an event listener (eg 'click') to a programatically added javascript generated code (every line of a table). Usually, I would normally do that with jQuery dirty on method, but it doesn't work (seems that my selector is too much specific. I don't know any way to do this in another way...

var STD.prototype.addTableWithEvent(id, eventName, eventFunction)
{
    var ident = "webapp_table_"+ id;
    var table = angular.element("<table id=\"#"+ ident +"\"></table>");
    var line = angular.element("<tr></tr>");

    // this is the line not working
    jQuery("body").on(eventName, '#'+ ident +' tr', { std: this }, eventFunction);

    line.appendTo(table);
    this.$compile(table)(this.$scope);
    table.appendTo('body');
};

This function is then called this way:

 var std = new STD();
 std.addTable("example", "click", function() { console.log("working"); });

The table is well added to the page, but the event function is not called when I click. If I change for this :

jQuery("body").on(eventName, 'tr', { std: this }, eventFunction);

Then it's working but for every table, which is not what I want. Is there a way to do this with Angular.js or jQuery?

Thanks!

Julien Fouilhé
  • 2,414
  • 3
  • 26
  • 50

2 Answers2

1

Try attaching the event to the table instead of the body, and set the selector to delegate it to the <tr> elements, like so:

 table.on(eventName, 'tr', { std: this }, eventFunction);
James Fair
  • 560
  • 1
  • 6
  • 18
0

Your code:

jQuery("body").on(eventName, 'tr', { std: this }, eventFunction);

will attach an event handler to every <tr> element on your page -- all tables. To narrow it down and be more specific, just use standard css selectors to narrow your selection.

Like this:

jQuery("body").on(eventName, '#desiredTableID tr', { std: this }, eventFunction);

or

jQuery(document).on(eventName, '#desiredTableID tr', { std: this }, eventFunction);
cssyphus
  • 31,599
  • 16
  • 79
  • 97
  • Look at my code, it is exactly what I am doing, and it doesn't work. – Julien Fouilhé Jan 23 '14 at 11:10
  • Glad you got it figured out. Honestly, I think you could also have solved it by binding to the `document` via `.on()` and specifying the precise table's `tr` that you wanted to target. However, very happy it is resolved. Generally, when you modify a DOM element (body, in your case, via the `append` method) you must then use `.on()` [against a DOM object or element higher in the hierarchy](http://stackoverflow.com/questions/1687296/what-is-dom-event-delegation). Also, if all `tr` elements on entire page are triggering, then be more specific, as above. Hope you experiment with this a bit. – cssyphus Jan 23 '14 at 17:09
  • Yes, may be I should have been adding it to the DOM before binding the events and it would have work. – Julien Fouilhé Jan 23 '14 at 21:19