Created
March 24, 2014 00:38
-
-
Save leomicheloni/9732208 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<script type="text/javascript" src="js/vendor/jquery/jquery.min.js"></script> | |
<script type="text/javascript" src="js/vendor/underscore/underscore.js"></script> | |
<script type="text/javascript" src="js/vendor/backbone/backbone.js"></script> | |
</head> | |
<body> | |
<div id="container"></div> | |
<script type="text/javascript"> | |
//definimos un modelo sin nada en especial | |
var Modelo = Backbone.Model.extend({ | |
defaults:{ | |
done: false | |
}, | |
validate: function(attributes){ | |
if(attributes.name.length===0) return "Name is required"; | |
} | |
}); | |
//definimos una vista, vamos a usar el div por defecto | |
//en "el" para agregarle datos del modelo | |
var Vista = Backbone.View.extend({ | |
initialize: function(){ //este método se ejecuta el crear una instancia | |
this.model.on("change", this.render, this); | |
//escuchamos el evento "change" de nuestro modelo | |
//y indicamos que cuando ocurra se ejecute el método | |
//"render" (el último parámetro es el contexto) | |
}, | |
template: '<div></div><input type="checkbox" />', | |
render: function(){ | |
this.$el.html(this.template); | |
this.$el.find("div").html(this.model.get("name")) | |
if(this.model.get("done")){ | |
this.$el.find(":checkbox").attr("checked", "checked"); | |
}else{ | |
this.$el.find(":checkbox").removeAttr("checked"); | |
} | |
return this; | |
}, | |
events:{ | |
"click :checkbox": function(){ //escuchamos el evento click | |
//sobre todo $el | |
this.model.set("done", this.$el.find(":checked").length===1); | |
} | |
} | |
}); | |
//creamos una instancia del modelo y asignamos la propiedad texto | |
var modelo = new Modelo({name: "comprar tornillos"}); | |
//instanciamos una vista y pasamos el modelo en el constructor | |
//utilizamos la propiedad model | |
var vista = new Vista({model: modelo}); | |
//renderizamos la vista | |
$("#container").append(vista.render().el); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment