Skip to content

Instantly share code, notes, and snippets.

@ivillamil
Created January 9, 2014 16:05
Show Gist options
  • Save ivillamil/8336654 to your computer and use it in GitHub Desktop.
Save ivillamil/8336654 to your computer and use it in GitHub Desktop.
Ejemplo sencillo de backbone que muestra las dos formas en las que se puede asignar un valor al attributo "el" de las vistas.
<!doctype html>
<html lang="es">
<head><title>Backbone</title></head>
<body>
<div id="app">
<form>
<input name="name" placeholder="Tu Nombre">
<button type="submit">Agregar</button>
</form>
<ul class="list"></ul>
</div>
<script type="text/template" id="itemTemplate">
<h2><%=name%></h2>
</script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min.js"></script>
<script>
var app = app || {};
app.ItemModel = Backbone.Model.extend({
defaults: { name: 'Juan' }
});
app.ItemView = Backbone.View.extend({
tagName: 'li',
template: _.template( $('#itemTemplate').html() ),
initialize: function(model) {
this.model = model;
return this;
},
render: function() {
this.$el.html( this.template( this.model.toJSON() ) );
return this;
}
});
app.AppView = Backbone.View.extend({
el: '#app',
events: {
"submit form": "addItem"
},
initialize: function() {
this.$list = this.$('ul.list');
this.$input = this.$('input');
},
addItem: function(e) {
e.preventDefault();
var newItemModel = new app.ItemModel({name: this.$input.val()});
this.$list.append( new app.ItemView(newItemModel).render().el );
this.$input.val('');
}
});
app.appView = new app.AppView();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment