Search code examples
jquerybackbone.jskeyup

converting a jQuery script in backbone


i need to understand how can i write this particular piece of jQuery code in the Backbone.js Version. This is the code that copies text or any input to some other div or field using the keyup() function.Since i am new to backbone i will be higly greatful if someone could sort this out

This is my index.html and the main.js code snippet

  <input type="text" name="Quantity" value="100"  id="quantity" />

$("#quantity").keyup(function () {
var value = $(this).val();
$("#quantity_img").text(value);}).keyup();

Solution

  • events is a event map. keyup #quantity is a event keyup on object #quantity. keyup is a function handler defined above.

    On render function fire keyup event.

    View = Backbone.View.extend({
      events: {
        'keyup #quantity': 'keyup'
      },
    
      keyup: function() {
        var value = this.$('#quantity').val();
        this.$("#quantity_img").text(value);
      },
    
      render: function() {
        this.$('#quantity').keyup();
      }
    });
    view = new View({el: $('#container')});
    view.render();
    

    Working example: https://jsfiddle.net/3z8sf113/1/