バックボーンの入力の変化を監視する方法は?
AngularJs で
<div ng-controller="W3">
<input type="text" ng-model="val" >
<p>{{val}}</p>
</div>
フィールドの値が に表示されていることを望みます<p></p>
。
バックボーンの入力の変化を監視する方法は?
AngularJs で
<div ng-controller="W3">
<input type="text" ng-model="val" >
<p>{{val}}</p>
</div>
フィールドの値が に表示されていることを望みます<p></p>
。
ビューにイベントとして追加する必要があります。
var MyView = Backbone.View.extend({
events: {
'keyup input': 'updateParagraph'
},
updateParagraph: function(ev) {
this.$('p').html(ev.target.value);
}
});
これは、ビューの HTML が質問にあるものと同じであることを前提としています。複数のイベントを使用する場合は、それぞれをハッシュに追加する必要があります。お気に入り:
events: {
'keyup input': 'updateParagraph',
'propertychange input': 'updateParagraph',
// etc.
}
ビューがモデルに関連付けられていて、入力がモデルを更新する必要がある場合は、代わりに次のように記述します。
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);
}
});
これにより、他のビューでモデルのその属性を変更した場合でも、それがその入力であるかどうかに関係なく、段落は更新されます。