javascript - Call function on object in underscore template -
i have button in html of template. how can make call function on object rendered @ time?
i realize this
refering button @ moment. how refer person?
template
<script type="text/template" id="tpl-person"> <tr> //... <td><button onclick="this.happybirthday()">birthday</button></td> </tr> </script>
javascript
var person = function(name, age){ //.... this.happybirthday = function(){ this.age ++; } this.render = function(){ var template = _.template($("#tpl-person").html()); $("#peoplewrapper").append(template(this)); } //constructor this.name = name; this.age = age; this.render(); }
why won't work
it not possible because attaching event handler html requires handler function serialized (i.e. in source form). there no real way serialize function in javascript, , if there showstopper: inside function this
reference existing javascript object impossible because again, needs serialized.
what can done instead
an easy workaround attach event handler jquery @ time template rendered.
taking consideration desired value of this
, can define event handler function within person
method as
// $.proxy because otherwise "this" clicked button element $.proxy(this.happybirthday, this);
attaching click handler straightforward:
var clickhandler = $.proxy(this.happybirthday, this); var html = $(template(this)); $("#peoplewrapper").append(html.find("button").click(clickhandler).end());
a better approach
that said, not way arrange things. consider different suggestion: attach person
object rendered template (e.g. through jquery's .data
) , refer within click handler; handler can delegated save on functions , allow dynamically adding more rendered templates.
for example:
the html template not attach handlers @ all.
when adding rendered template use .data
associate person object , mark person-associated visible dom perspective. simple adding data-person
attribute (or css class):
$("#peoplewrapper").append( $(template(this)).data("person", this).attr("data-person", ""));
attach delegated handler dom recognizes clicks on buttons and, starting clicked element, finds associated person object , calls happybirthday
method:
$("#peoplewrapper").on("click", "[data-person] button", function() { $(this).closest("[data-person]").data("person").happybirthday(); });
Comments
Post a Comment