JSFiddle - React, Tailwind, and code Playground
by tdecs
HTML
<script src="https://raw.github.com/documentcloud/underscore/master/underscore.js"></script>
<script src="https://raw.github.com/documentcloud/backbone/master/backbone.js"></script>
<script type="text/template" id="main">
<p>Name: <%= user.name %></p>
<p>Company name: <%= company.companyName %></p>
<p>Car make: <%= car.carMake %></p>
<p>Fek: <%= fek %></p>
</script>
<script type="text/template" id="company">
<p>Company name: <%= companyName %></p>
<p>Fek: <%= fek %></p>
<button>Change company name</button>
</script>
<script type="text/template" id="car">
<p>Car make: <%= carMake %></p>
<p>Fek: <%= fek %></p>
</script>
<div id="mainContainer"></div>
<div id="companyContainer"></div>
<div id="carContainer"></div>
CSS
div { margin: 20px; border:1px solid #aaa; padding:10px;-webkit-user-select: none; cursor: default; }
JavaScript
var MainModel = Backbone.Model.extend({
defaults: {
user: {
name: 'denis'
},
company: {
companyName: 'bbva'
},
car: {
carMake: 'Toyota'
},
fek: 0
}
});
function createModelFromKey(model, key) {
var newModel = Backbone.Model.extend({
defaults: model.get(key)
});
return new newModel;
};
var baseView = Backbone.View.extend({
events: {
'click': 'updateFek'
},
updateFek: function() {
var fek = this.model.get('fek');
fek++;
this.model.set({
fek: fek
});
}
});
var baseSubView = baseView.extend({
events: {
'click': 'updateFek',
'click button': 'changeCompanyName'
},
initialize: function() {
_.bindAll(this);
this.subModel = createModelFromKey(this.model, this.moduleId);
this.template = _.template($(this.template).html());
this.model.on('change', this.render);
this.render();
},
render: function() {
// solo para pintar fek en el template
this.subModel.set({
fek: this.model.get('fek')
}, {
silent: true
});
var tmpl = this.template(this.subModel.toJSON());
this.$el.html(tmpl).appendTo('#' + this.moduleId + 'Container');
},
changeCompanyName: function() {
if (this.subModel.get('companyName')) {
var newCompanyName = prompt('Enter new Company name:');
this.subModel.set({
companyName: newCompanyName
});
// just if we want to update the whole model
this.model.set({
company: {
companyName: newCompanyName
}
});
}
}
});
var mainView = baseView.extend({
template: '#main',
moduleId: 'main',
initialize: function() {
_.bindAll(this);
this.model = new...