Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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