I am trying to create a switch view using backbone js and found that the binding event is fired several times when I switch the view several times.
Below is the code for a better illustration:
HTML
<div id='container'> halo world </div> <button id='but1'>red view</button> <button id='but2'>blue view</button>
CSS
#red_view{ width:400px; height:400px; background-color:red; } #blue_view{ width:400px; height:400px; background-color:blue; } .button,.button2{ width:300px; height:300px; background-color:gray; }
Javascript
RedView = Backbone.View.extend({ el: "#container", events:{"click .button":"clickme"}, clickme:function(){ alert('redview'); }, initialize: function(){ this.$el.html("<div id='red_view'><div class='button'>Click Me</div></div>"); } }); BlueView = Backbone.View.extend({ el: "#container", events:{"click .button2":"clickme2"}, clickme2:function(){ alert('blueview'); }, initialize: function(){ this.$el.html("<div id='blue_view'><div class='button2'>Click Me</div></div>"); } }); $(document).ready(function(){
If you click on the red view 3 times and click "click me." It will also appear 3 times. I suspect that somewhere you need to untie the event, but could not find the right way to do this. It is best to give some recommendations regarding proper implementation.
Here is a link to jsfiddle demo. http://jsfiddle.net/mochatony/DwRRk/31/
source share