- Router 代码
var MyRouter = Backbone.Router.extend({
routes: {
// Other Routers
"muppets/:id": "getMuppet"
},
getMuppet: function (id) {
console.log("fetch muppet: " + id);
var muppet = new MuppetModel({id: id});
muppet.fetch().then(function () {
console.log(muppet.get('name'));
var muppetView = new MuppetsListItemView({model: muppet, el: $('#muppets-list')});
muppetView.render()
});
}
});
MuppetsListItemView
代码
var MuppetsListItemView = Backbone.View.extend({
tagName: 'li',
className: 'muppet',
template: _.template($('#muppet-item-tmpl').html()),
initialize: function() {
this.listenTo(this.model, 'destroy', this.remove)
},
render: function() {
var html = this.template(this.model.toJSON());
console.log(html, 'html of the itemView');
this.$el.html(html);
return this;
},
events: {
'click .remove': 'onRemove'
},
onRemove: function() {
this.model.destroy();
}
});
- Template
<script type="text/template" id="muppet-item-tmpl">
<p><a href="/#muppets/<%= id %>" class=".showSingle"><%= name %></a></p>
<p>Job: <i><%= occupation %></i></p>
<button class="remove">x</button>
</script>