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's tagname, 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:

  1. let rowviews create , own own els. keep tagname , classname attributes in rowview , stop passing el constructor. should change $(this.el) this.$el too, there's no need create jquery object when backbone has stashed 1 away you.

  2. return this rowview's render, standard practice , makes next step bit nicer.

  3. whatever creates rowviews should create them, render them, , put them inside container. appear trying use mountpoint (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 (or var $mountpoint = $(mountpoint) above foreach , 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

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -