Weitere ähnliche Inhalte
Ähnlich wie Study Intro Backbone (20)
Study Intro Backbone
- 3. MVC
M Model
!
V View
!
C Collection
( not Controller)
- 4. MVC 構図(一例)
Model
View
render
Collection
Model
View
render
Model
View
render
el el el document
- 5. メリット
• フロントエンドを構造化できる
• 属性(attributes)の変化にしたがって描画を制
御できる
• 各処理を担当する箇所を明確にできる
• 通信部分、イベント管理、バリデーション、
描画
- 7. Depend on …
UnderScore
(jQuery)
(Handlebars)
<script src="lib/js/jquery-1.9.1.js"></script>
<script src=“lib/js/underscore.js”></script>
<script src="lib/handlebars.js"></script>
<script src="lib/js/backbone.js"></script>
- 8. Model
var App = {};
App.Models = {};
App.Models.Mymemory = Backbone.Model.extend({
// new したときに走る処理
initialize: function(){
// attributesに新しい値がセットされたときのchangeイベントにbind
this.on(“change”, function(){ alert(“変更しました”); });
},
// newしたときのattributes初期値
defaults: {
watch_name: '',
clickable: false,
},
// save したときにAjax通信するURL
url: "/mymemory/watch"
});
!
var mymemory = new App.Models.Mymemory({watch_name: “みてる”});
- 9. View
var App = {};
App.Views = {};
App.Views.MymemoryView = Backbone.View.extend({
// viewを書き出す位置
el: “js-mymemory-view”,
initialize: function(){
// 紐付いているmodel のchangeイベントを購読してrender()する
this.listenTo(this.model, “change”, this.render);
},
render: function(){
var json = this.model.attributes;
var html = App.Views.MymemoryView.template(json);
this.$el.html(html);
return this;
},
events: {‘click .js-clickable’ : ‘updateNextWatch’},
updateNextWatch: function(){
this.model.set({watch_name: “みた”});
}
}, {
// handlebars を利用したview テンプレート
template: Handlebars.compile($("#mymemory-template").html())
});
!
new App.Views.MymemoryView({model: mymemory}).render();
- 10. View template
<script id="mymemory-template" type="text/x-handlebars-
template">
{{#if clickable}}
<button class="js-clickable">{{watch_name}}</button>
{{else}}
<span>{{watch_name}}
<a class="js-mymemory-to-quit" href="#">✕</a>
</span>
{{/if}}
</script>
- 11. Collection
var App = {};
App.Collections = {};
App.Collections.Mymemories= Backbone.Collection.extend({
model: App.Models.Mymemory
});
var mymemories = new App.Collections.Mymemories()
!
mymemories.add( new App.Models.Mymemory() );