javascript - How to avoid double event binding in Backbonejs View? -
var rowview = backbone.view.extend({ tagname: 'li', classname: 'course-row', events: { "click .table-row": "rowclick" // problem here! }, initialize: function() {}, template: _.template(tpl), render: function() { var rowstr = this.template({course: this.model}); $(this.el).append(rowstr); }, rowclick: function (e) { alert(e); } });
above code defines backbone row view. i'd create , render several several rows in table, did:
data.foreach(function(rowdata){ var row = new rowview({model: course, el: mountpoint}); row.render(); });
if create 2 rows, event bind twice( 2 alert msg if click on row), 3 rows 3 times. avoided problem defining event @ parent views, if need attach event handler @ each row, how avoid double event biding problem?
you're doing this:
data.foreach(function(rowdata){ var row = new rowview({model: course, el: mountpoint}); row.render(); });
that means view ignore tagname
, classname
, go ahead , bind el
supply because:
this.el
can resolved dom selector string or element; otherwise created view'stagname
,classname
,id
,attributes
properties.
a view's events
bound el
using delegation , you're binding multiple views (which happen same view "class") of course you're getting multiple event bindings.
if rows supposed <li class="course-row">
elements want couple things:
let
rowview
s create , own ownel
s. keeptagname
,classname
attributes inrowview
, stop passingel
constructor. should change$(this.el)
this.$el
too, there's no need create jquery object when backbone has stashed 1 away you.return
this
rowview
'srender
, standard practice , makes next step bit nicer.whatever creates
rowview
s should create them,render
them, , put them inside container. appear trying usemountpoint
(which presumable<ul>
) container want say:data.foreach(function(rowdata) { var row = new rowview({model: course}); mountpoint.append(row.render().el); // why (2) above -----^^^ });
that assumes
mountpoint
jquery instance, if that's not case you'd want$(mountpoint).append(row.render().el)
instead (orvar $mountpoint = $(mountpoint)
aboveforeach
, use$mountpoint.append
inside it).
a personal rule of thumb: if you're passing el
view constructor you're making mistake. if know why you're passing el
constructor, know consequences, , know how deal them you're adult enough run scissors go right ahead.
Comments
Post a Comment