1

suppose I have this template:

<script type="text/html" id="list_tpl">
<ul>
{{#list}}
    <li><input value="{{ name }}" /><a href="javascript:void(0);">delete</a></li>
{{/list}}
</ul> 
</script>  

render:

Mustache.to_html(document.getElementById("list_tpl").innerHTML), {
    "list": [
        {"name": "a1"},
        {"name": "a2"},
        {"name": "a3"}
    ]
});

I'd like to bind a event that when the delete link in each <li> is clicked, that <li> gets removed from the DOM.
I know I could bind event after the render is complete, but as the render will happen several times(every time the user click a button), I don't want to bind it every time.
How to do that nicely?

wong2
  • 34,358
  • 48
  • 134
  • 179

2 Answers2

3

I'm not sure how to do it with plain javascript, but Jquery has .live() http://api.jquery.com/live/

from that website: "Attach a handler to the event for all elements which match the current selector, now and in the future."

That's exactly what you're asking.

Here's some related info on SO how to do it in plain javascript: jQuery live() in plain JavaScript?

hth,

Community
  • 1
  • 1
Geert-Jan
  • 18,623
  • 16
  • 75
  • 137
  • 1
    @wong2: If you do start using jQuery, I advise you to rather use `.delegate` than `.live`. There are many posts (even here on Stackoverflow) that explain the benefits. – Robert Koritnik Oct 11 '11 at 11:14
  • @Robert: ahh didn't know that thanks.. One of the more popular comparisons seems to be : http://stackoverflow.com/questions/4204316/jquery-live-vs-delegate – Geert-Jan Oct 11 '11 at 11:17
  • No, I can't use jquery in this project...but thanks for the knowledge – wong2 Oct 11 '11 at 14:09
0

For the ones that landed this topic after google search and still looking for an answer: you can use jQuery to manage delegation with "on" method.

As of jQuery 3.0, both delegate and live methods are depreciated.

jQuery docs suggest to use "on" method instead of delegate and live methods, there is another topic for using "on" method with future elements: jQuery .on function for future elements, as .live is deprecated

Community
  • 1
  • 1
fsakar
  • 21
  • 2