2 way binding input field
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--<link href="css/style.css" rel="stylesheet">-->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
</head>
<body>
<label>Name:</label>
<input type="text" placeholder="Enter a name here">
<h1></h1>
<!--<script type="text/javascript" src="main.js"></script>-->
<script>
'use strict'
let NameModel = Backbone.Model.extend({
defaults: {
greetings: 'Hello ',
name: ''
}
});
let nameModel = new NameModel();
nameModel.on('change', function (model, options) {
console.dir('name: ' + model.get('name'));
});
let MyView = Backbone.View.extend({
el: 'body',
// https://www.w3schools.com/jsref/dom_obj_event.asp
// DOM events start with 'on', Backbone event don't.
events: {
'input input': 'onInput',
},
initialize: function () {
console.log('View initialized');
this.render();
},
render: function () {
this.$el.find('h1').text(this.model.get('greetings'));
return this;
},
onInput: function () {
let inputText = this.$el.find('input').val();
//update model
this.model.set('name', inputText);
//update view
this.$el.find('h1').text(this.model.get('greetings') + inputText);
}
});
let inputView = new MyView({
model: nameModel
});
</script>
</body>
</html>