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>
.
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>
.
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.