Button Onclick event and backbone.js view

29,662

You're supposed to setup your event handlers in your Backbone.View.

HTML (added id="myButtons" to container div)

<div class="button1" id="myButtons">
  <button class="first" class="button-up">Go Up</button>
  <button class="last" class="button-down">Go Down</button>
</div>

JavaScript (added events)

var BlahView = Backbone.View.extend({

  events: {
    "click .button-up": "transitionUp",
    "click .button-down": "tranistionDown",
  },

  transitionUp: function() {
    console.log("Transition up");
  },

  tranistionDown: function() {
    console.log("Transition down")
  }

});

var blahView = new BlahView({ el: $('#myButtons') });

By specifying onclick attributes, your browser is expecting functions called transitionUp and transitionDown in the global scope. Your methods are defined in an object. Binding event handlers with HTML attributes is generally discouraged, especially if you're using Backbone (since you can't easily bind events to specific instances of your views).

Share:
29,662
Admin
Author by

Admin

Updated on October 09, 2020

Comments

  • Admin
    Admin over 3 years

    I current have an html file with the following:

    <div class="button1">
    
        <button class="first" id="up" onclick="tranistionUp">
           Go Up
        </button>
    
        <button class="last" id="down" onclick="tranistionDown">
           Go Down
        </button>
    </div>
    

    I have the following in a backbone.js view file:

    var BlahView = BackBone.View.extend({
      initialize:function(){},
      blah...
      blah...
     transitionUp: function(){
        blah...
     },
     tranistionDown: function(){
    },
    render:function (){
        blah....
    }; 
    });
    

    When I click on the buttons I am seeing an undefined function error for both functions, I am new to backbone any assistance would be great.

  • Tim Child
    Tim Child over 8 years
    Should be var BlahView = Backbone.View.extend({ its one word leading caps only