Skip to content

Instantly share code, notes, and snippets.

@andyyou
Created May 10, 2013 06:51
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 andyyou/5552806 to your computer and use it in GitHub Desktop.
Save andyyou/5552806 to your computer and use it in GitHub Desktop.
backbone sample
<!doctype html>
<html>
<head>
<title>Hello Backbone</title>
</head>
<body>
<button id="check">Check</button>
<ul id="list"></ul>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script>
<!--
jQuery 說明: (function(){ })(jQuery) 和 $(function(){ }) 的差異是前者不需要已存在的 DOM 常用在擴充套件,而後者需要。
-->
(function($){
// 定義 Model 類別。
var World = Backbone.Model.extend({
name: null
});
// 類似 C# : List<World> Worlds,但可以在做初始化設定。
var Worlds = Backbone.Collection.extend({
initialize: function(models, options)
{
this.bind('add', options.view.addOneWorld);
}
});
// 定義 AppView 類別
AppView = Backbone.View.extend({
el: $('body'),
initialize: function(){
this.worlds = new Worlds(null, {view: this})
},
events:{
"click #check": "check_click"
},
check_click: function()
{
var world_name = prompt('Please enter your name?');
if(world_name == "") world_name = 'unknown';
var world = new World({name: world_name});
this.worlds.add(world);
},
addOneWorld: function(model){
$('#list').append("<li>Say : <b>" + model.get('name') + "</b> Hello!</li>")
}
});
var appview = new AppView;
})(jQuery);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment