2
votes

How do I add more events after rendering a collection to a view.

I have a list of all the element Ids which need an event binded to them.

Currently I am trying to use jQuery onclick to trigger a callback to a function in my view.

The problem though is that the function call in my view is undefined inside the jQuery click event.

I looked at the Backbone docs and it says to use delegateEvents however the documentation does not show examples ....

http://documentcloud.github.io/backbone/#View-delegateEvents

//add more dynamic events for the rendered employee list 
    addMoreEvents: function ()
    {
        console.log("List View - Add More DOM Events");


        for (var i = 0; i < this.employees.models.length; i++)
        {
            var element = "#" + this.employees.models[i].attributes.id;
            //bind event that when user clicks on <li> on employeelist , it will go fetch all the tasks for that employee
            $(element).click(this.getEmployeeInfo()); //not working!
        }


    }

There must be an easy way to do this for adding events to elements that exist after being rendered.

Thanks

1

1 Answers

2
votes

You're going about this the wrong way. Instead of trying to bind directly to click events on #some-id elements, you should attach a class to the things you want to click on and then bind click handlers to elements of that class using the view's normal events object.

For example, you'd have something like this in the HTML inside your view's el:

<li class="item" id="6">Where</li>
<li class="item" id="11">is</li>
<li class="item" id="23">pancakes</li>
<li class="item" id="42">house?</li>

and then you'd have events like this in your view:

events: {
    'click .item': 'getEmployeeInfo'
}

Then your click handler, getEmployeeInfo, can look at ev.currentTarget.id to get the id attribute of the clicked item:

getEmployeeInfo: function(ev) {
    var id = ev.currentTarget.id; // this will be the model's `id`
    // do whatever needs to be done...
}