Skip to content

Instantly share code, notes, and snippets.

@foo9
Last active December 20, 2015 14:48
Show Gist options
  • Select an option

  • Save foo9/6149160 to your computer and use it in GitHub Desktop.

Select an option

Save foo9/6149160 to your computer and use it in GitHub Desktop.
Backbone.jsでModelによってViewを分ける
var App = {
Views: {},
Models: {},
Collections: {}
};
App.Models.Item = Backbone.Model.extend({
defaults: function() {
return {
viewtype: '',
color: '',
name: ''
};
}
});
App.Collections.Items = Backbone.Collection.extend({
model: App.Models.Item
});
App.Views.Item = Backbone.View.extend({
tagName: 'li',
template: _.template('<p>My name is <%= name %>.</p>'),
decorate: function() {},
prerender: function() {
this.$el.html(this.template(this.model.toJSON()));
this.decorate();
return this;
}
});
App.Views.HogeItem = App.Views.Item.extend({
// override
decorate: function() {
this.$el.css({
color: '#f00'
});
},
render: function() {
this.prerender();
return this;
}
});
App.Views.FugaItem = App.Views.Item.extend({
// override
decorate: function() {
this.$el.css({
color: '#00f',
fontStyle: 'italic',
});
},
render: function() {
this.prerender();
return this;
}
});
App.Views.PiyoItem = App.Views.Item.extend({
// override
decorate: function() {
this.$el.css({
color: '#0f0',
textDecoration: 'underline'
});
},
render: function() {
this.prerender();
return this;
}
});
App.Views.Items = Backbone.View.extend({
tagName: 'ul',
getDom: function(view) {
return view.el;
},
renderView: function(model) {
var type = model.get('viewtype');
return new App.Views[type]({ model: model }).render();
},
render: function() {
var views = this.collection.map(this.renderView, this);
var dom = _.map(views, this.getDom, this);
this.$el.html(dom);
return this;
}
});
App.Views.App = Backbone.View.extend({
initialize: function() {
this.items = new App.Views.Items({
collection: new App.Collections.Items([
{ viewtype: 'HogeItem', name: 'ほげ' },
{ viewtype: 'FugaItem', name: 'ふが' },
{ viewtype: 'PiyoItem', name: 'ぴよ' }
])
});
},
render: function() {
this.$el.append( this.items.render().el );
return this;
}
});
$(function() {
var app = new App.Views.App({ el: '#sample' });
app.render();
});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.1/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div id="sample"></div>
</body>
</html>
@foo9
Copy link
Copy Markdown
Author

foo9 commented Aug 4, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment