Backbone Modelbinder Passing View reference
by niki4810
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>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<script src="https://raw.github.com/josscrowcroft/accounting.js/master/accounting.js"></script>
Type Some Value Here :<div class="container"></div>
JavaScript
$(function () {
var InputView = Backbone.View.extend({
render: function () {
var html = '<input type="text" name="totalAmount"/>';
this.$el.html(html);
return this;
},
inputConverter: function (direction, value) {
var viewEl = this.viewEl;
var symbol = viewEl.model.get("symbol");
if (direction === "ModelToView") {
//format only when the direction is from model to view
return accounting.formatMoney(value,symbol);
} else {
//from view to model, just store the plain value
return value;
}
}
});
var ContainerView = Backbone.View.extend({
_modelBinder: undefined,
tagName: "span",
initialize: function () {
this._modelBinder = new Backbone.ModelBinder();
},
close: function () {
this._modelBinder.unbind();
},
render: function () {
var currentInputViewModel = new Backbone.Model();
currentInputViewModel.set({
"symbol": "€"
});
var currentInputView = new InputView({
model: currentInputViewModel
});
this.$el.append(currentInputView.render().$el);
var bindings = {
"totalAmount": {
"selector": '[name = "totalAmount"]',
"converter": currentInputView.inputConverter,
"viewEl": currentInputView //Passing views reference
}
};
//call modelBinder bind api to apply bindings on the current view
this._modelBinder.bind(
this.model /*the model to bind*/ ,
this.el /*root element*/ ,
bindings /*bindings*/ );
return this;
}
});
var ContainerModel = new...