Skip to content

Instantly share code, notes, and snippets.

@lqt0223
Last active April 6, 2017 02:22
Show Gist options
  • Save lqt0223/640e8b6d73b713c9c2905b0c566d18b0 to your computer and use it in GitHub Desktop.
Save lqt0223/640e8b6d73b713c9c2905b0c566d18b0 to your computer and use it in GitHub Desktop.
13 Backbone tiny demo - using the purest MVC framework
<html>
<head>
<title></title>
</head>
<body>
<input id="input">
<!-- The DOM that will be binded later -->
<div id="app"></div>
<!-- The template -->
<script type="text/template" id="temp">
<p><%= data %></p>
</script>
<!-- The refereced libraries -->
<script src="http://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="http://cdn.bootcss.com/underscore.js/1.8.3/underscore.js"></script>
<script src="http://cdn.bootcss.com/backbone.js/1.3.3/backbone.js"></script>
<script type="text/javascript">
// The Model
var AppModel = Backbone.Model.extend({});
// The View
var AppView = Backbone.View.extend({
// which DOM element to bind the app view to
el: "#app",
// the _.template() will return a template generation function which receive model value as parameter to render DOM
template: _.template($("#temp").html()),
initialize: function(){
// the view will listen to its model modification, and render the DOM again
this.listenTo(this.model, "change", this.render);
},
// on app start or data update, call this
render: function(){
this.$el.html(this.template({data: this.model.get("data") }));
}
});
var app = new AppView({
model: new AppModel()
});
$("#input").bind("input", function(e){
app.model.set("data", e.target.value);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment