Event does not bind when dynamically adding view

I have two simple views: one with a button that creates a view and adds it to the page. The new view consists of one list item with a link and an event that I need to bind to each item in the list. I think the problem here is in the el object. What should I read el-object should be created automatically when it is not defined when building the view? See this script

HTML:

<div id="main"> <button type="button" class="add">Add view</button> <ul id="tasks" /> </div> <script id="view-template-new-task" type="text/html"> <li><a href="#" class="fire">Task</a></li> </script> 

JS:

 var TaskView = Backbone.View.extend({ events: { 'click a.fire': 'fire' }, fire: function() { alert('fire'); }, initialize: function() { this.template = _.template($('#view-template-new-task').html()); }, render: function() { $('#tasks').append(this.template()); } }); var View = Backbone.View.extend({ events: { 'click button.add': 'addView' }, addView: function(e) { var task = new TaskView(); task.render(); } }); $(function() { var view = new View({ el: $('#main') }); });​ 
+4
source share
1 answer

The array automatically delegates events to the view element. As is the case, el in your TaskView points to an unattached div (by default, el created by Backbone), not an item in your list.

The cure is simple: create a subheading with its e-grid to the correct DOM node, setting tagName to li and adding this element to your main view.

 var TaskView = Backbone.View.extend({ tagName: 'li', events: { 'click a.fire': 'fire' }, fire: function() { alert('fire'); }, initialize: function() { this.template = _.template($('#view-template-new-task').html()); }, render: function() { this.$el.html(this.template()); return this; } }); var View = Backbone.View.extend({ events: { 'click button.add': 'addView' }, addView: function(e) { var task = new TaskView(); this.$('#tasks').append(task.render().el); } }); 

And the updated Fiddle http://jsfiddle.net/BLP6J/31/

+5
source

All Articles