Search code examples
javascripthandlebars.jsyui

How to set onclick with Handlebars and YUI?


I'm using the handlebars module from YUI to do some templating for my app, I've written this method for templating:

var source = '<ol>{{#items}}<li style="width:400px;">' +
    '{{{name}}} done <button class="btn btn-primary">remove # {{@index }}</button> </li>{{/items}}</ol>';

var compileList = function() {
        var html = Y.Handlebars.render(source, {
            items: itemArray
        });

        Y.one('#my-list').setContent(html);
}

And I would like each button within the li to have the following function as it's on-click:

var removeList = function(index) {
    itemArray.splice(index);
    compileList();
};

Is this possible with handlebars and YUI ?


Solution

  • I'd suggest using event delegation (http://yuilibrary.com/yui/docs/event/delegation.html), along these lines:

    Y.one('#my-list').delegate('click', function (ev) {
        // do stuff here
    }, 'button');
    

    You'll need 'node-event-delegate' in your use() call, if it's not already there.

    The 'do stuff here' would be the body of your function, except that you'll need to work out the index you need.

    Event delegation is better because you only add one event listener, no matter how many li's you have. The event listener sits above the target elements (the li's) and waits for events to bubble up the DOM to it. If that makes sense - if not there's better explanations on the YUI site.