ModelBinder example 2
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.modelbinder/0.1.3/Backbone.ModelBinder-min.js"></script>
<br>
Model data: <div id="modelData"></div>
<hr><br>
<div id="viewContent"></div>
JavaScript
$().ready(function () {
dogs = new Backbone.Collection({model:Backbone.Model});
dogs.add({id:1, name:'Andy', collar: 'yellow'});
dogs.add({id:2, name:'Biff', collar: 'red'});
dogs.add({id:3, name:'Candy', collar: 'green'});
var phoneConverter = function (direction, value) {
if (direction === Backbone.ModelBinder.Constants.ModelToView) {
var formattedPhone = '';
if (value) {
formattedPhone = value.replace(/[^0-9]/g, '');
if (formattedPhone.length == 7) {
formattedPhone = formattedPhone.substring(0, 3) + '-' + formattedPhone.substring(3, 7);
}
else if (formattedPhone.length == 10) {
formattedPhone = '(' + formattedPhone.substring(0, 3) + ') ' + formattedPhone.substring(3, 6) + '-' + formattedPhone.substring(6, 10);
}
else if (formattedPhone.length == 11 && formattedPhone[0] === '1') {
formattedPhone = '1 (' + formattedPhone.substring(1, 4) + ') ' + formattedPhone.substring(4, 7) + '-' + formattedPhone.substring(7, 11);
}
}
return formattedPhone;
}
else {
return value.replace(/[^0-9]/g, '');
}
};
model = new Backbone.Model({firstName:'Bob', graduated:'maybe', phone: '1234567'});
model.bind('change', function () {
$('#modelData').html(JSON.stringify(model.toJSON()));
});
model.trigger('change'); // just to show the #modelData values initially, not needed for the ModelBinder
ViewClass = Backbone.View.extend({
_modelBinder:undefined,
initialize:function () {
this._modelBinder = new Backbone.ModelBinder();
},
render:function () {
var html = '\
Edit your information:<br><br>\
First Name: <input type="text" name="firstName"/><br>\
Last Name: <input type="text" name="lastName"/><br>\
Phone:...