Search code examples
jqueryjquery-templates

Bound events lost in nested template (?)


I'm facing a problem here and I'm not sure whether it's a bug or my stupidness.

I've build a widget, based on this template:

<!--  TEMPLATE A  -->
<div class="mplc-widget"> 
 <div class="mplc-widget-available">
  <div class="mplc-widget-header">Available options</div>
  <div class="mplc-widget-middle"><input></input></div>
  <div class="mplc-widget-choices">
   <table>
    {{each(i, choice) choices}}
     <tr name="${choice[0]}">
      <td>${choice[1]}</td>
     </tr>
    {{/each}}
   </table>
  </div>
 </div>
 <div class="mplc-widget-selector">
  <div><button>A</button></div>
  <div><button>B</button></div>
 </div>
 <div class="mplc-widget-chosen">
  <div class="mplc-widget-header">Selected options</div>
  <div class="mplc-widget-choices">
   <table>
   </table>
  </div>
 </div>
</div>

after rendering this template (with widget = $.tmpl(...)) button A and button B are bound to a click event, like this:

$('button', widget).bind('click', function(){alert('Hello world!');})

Then widget is returned. The functions which renders the previous template and binds the events, is being called in another template:

<!-- TEMPLATE B -->
<div class='form'>
 <table>
  {{each(i, field) fields}}
   <tr>
    {{if field.fieldname}}
     <p>
      <td {{if field.required}} class='field-required'{{/if}}>
       ${field.label}:</td> <td>{{tmpl field.create()}}
       {{if field.help_text}}<br/><span class='help_text'>${field.help_text}</span>{{/if}}
      </td>
     </p>
    </tr>
   {{/if}}
  {{/each}}
 </table>
</div>

In this template {{tmpl field.create()}} represents the function which renders and returns template A. All the element are displayed fine when inserted into the DOM, but the bind function (set in create) are lost!

Is this the correct behaviour or am I doing something completely wrong?


Solution

  • Well, I'm still not able to apply the logic explained above. However: I was able to apply a workaround, using livequery. It is not ideal, but it works.