0

How to monitor change in input in backbone?

In AngularJs

 <div ng-controller="W3">

     <input type="text" ng-model="val" >

     <p>{{val}}</p>
 </div>

I want that field value has been displayed in <p></p>.

jeremy
  • 9,965
  • 4
  • 39
  • 59
Michael Phelps
  • 3,451
  • 7
  • 36
  • 64
  • Check out this:- http://stackoverflow.com/questions/1948332/detect-all-changes-to-a-input-type-text-immediately-using-jquery –  Aug 03 '13 at 14:53
  • Thank you very much. This is a great link about jquery.I am now studying the possibility of Backbone and interested in whether it is possible to repeat similar means by baCKBONE – Michael Phelps Aug 03 '13 at 14:58

1 Answers1

2

You have to add it as an event on your view:

var MyView = Backbone.View.extend({
    events: {
        'keyup input': 'updateParagraph'
    },
    updateParagraph: function(ev) {
        this.$('p').html(ev.target.value);
    }
});

This assumes that your HTML for the view is just like what you have in your question. If you want to use multiple events, you will need to add each one to the hash. Like:

events: {
    'keyup input': 'updateParagraph',
    'propertychange input': 'updateParagraph',
    // etc.
}

And if your view is tied to a model and the input should update the model, I would write it this way instead:

var MyView = Backbone.View.extend({
    initialize: function() {
        this.listenTo(this.model, 'change:text', this.updateParagraph);
    },
    events: {
        'keyup input': 'updateModel'
    },
    updateModel: function(ev) {
        var target = ev.target;
        // Assuming that the input name is the model attribute
        // To simplify, I'm just going to set something specific
        this.model.set('text', target.value);
    },
    updateParagraph: function(model, value) {
        // Set the input value as well, so it stays in sync
        this.$('input').val(value);
        this.$('p').html(value);
    }
});

That makes it so that if you change that attribute on the model in any other view, the paragraph would still update, regardless of whether it was that input or not.

kalley
  • 18,072
  • 2
  • 39
  • 36
  • No problem. I also updated my answer to include a version of the view that updates a model and keeps the view in sync with the model even if it changes elsewhere. – kalley Aug 03 '13 at 16:02