您的位置:首页 > Web前端 > JavaScript

Backbone.js 显示Collection里面的一个元素

2017-12-21 08:54 309 查看
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;
},
4000

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  backbone.js