Skip to content

Instantly share code, notes, and snippets.

@takeshy
Created December 31, 2012 03:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takeshy/4417183 to your computer and use it in GitHub Desktop.
Save takeshy/4417183 to your computer and use it in GitHub Desktop.
Backbone.jsのView機能をローカルで実現できるようにしたSample
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://underscorejs.org/underscore-min.js"></script>
<script type="text/javascript" src="https://raw.github.com/LearnBoost/socket.io-client/master/dist/socket.io.min.js"></script>
<script type="text/javascript" src="http://backbonejs.org/backbone-min.js"></script>
<script type="text/javascript">
jQuery(function() {
//Model
var CounterModel = Backbone.Model.extend({
defaults: {counter: 0}
});
//View
var ExampleView = Backbone.View.extend({
//el: "<div/>", Backbone.jsのデフォルト
template: _.template($("#sample_template").html()),
events: {
"click #ignore": "ignore"
},
initialize: function(){
this.model = new CounterModel();
//this.model.on("change",this.render,this);
this.listenTo(this.model,"change",this.render);
var self = this;
window.setTimeout(
function(){
var counter = self.model.get("counter") + 1;
self.model.set("counter",counter);
console.log(counter);
if(counter < 100){
window.setTimeout(arguments.callee,1000);
}
},1000);
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
},
ignore: function(){
this.model.off("change");
}
});
//Route
var ExampleRouter = Backbone.Router.extend({
routes: {
".*": "show"
},
show: function(){
var view = new ExampleView();
$("#contents").html(view.render().el);
}
});
window.router = new ExampleRouter();
Backbone.history.start();
});
</script>
</head>
<body>
<script type="text/html" id="sample_template">
<input type="button" id="ignore" value="無視" />
<p> Counter is <%= counter %></p>
</script>
<div id="contents"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment