我有一个带有主干的标准列表视图设置,如下所示。我有一个需要删除项目的实例,这是在删除模型并取消渲染元素的删除函数中完成的。然而,就在销毁/取消渲染之前,我想选择列表中的前一个元素。
有没有一种在骨干网中执行此操作的好方法,现在我唯一能想到的就是使用一些 jQuery 来实现,但我想知道是否有办法在骨干网内部执行 prev/next。还是在附加列表项时需要手动设置?
App = (function(Backbone, _){
var Item = Backbone.Model.extend(
{
defaults:
{
part1: 'hello',
part2: 'world'
}
});
var ItemList = Backbone.Collection.extend({
model: Item
});
var ListRow = Backbone.View.extend(
{
tagName: 'li',
initialize: function()
{
_.bindAll(this, 'render');
},
render: function()
{
$(this.el).html('<span>'+this.model.get('part1')+' '+this.model.get('part2')+'</span>');
return this;
},
remove: function()
{
//toggle previous element if exists before destory
$this.model.destroy();
},
toggle: function()
{
this.$el.addClass('active');
}
});
var ListView = Backbone.View.extend(
{
el: $('#layout_content'),
events:
{
'click button#add': 'addItem'
},
initialize: function()
{
_.bindAll(this, 'render', 'addItem', 'appendItem');
this.collection = new TableList();
this.collection.bind('add', this.appendItem);
this.counter = 0;
this.render();
},
render: function()
{
var self = this;
$(this.el).append("<button id='add'>Add list item</button>");
$(this.el).append("<ul></ul>");
_(this.collection.models).each(function(item){ // in case collection is not empty
self.appendItem(item);
}, this);
},
addItem: function()
{
this.counter++;
var item = new Item();
item.set({part2: item.get('part2') + this.counter});
this.collection.add(item);
},
appendItem: function(item)
{
var listRow = new ListRow({
model: item
});
$('ul', this.el).append(listRow.render().el);
}
});
var app = function(initialModels)
{
this.start = function()
{
this.listView = new ListView({collection: new ItemList(initialModels)});
};
};
return app;
})(Backbone, _);
var app = new App([{"id":"95","note_title":"can we find the title"},{"id":"93","note_title":"some title"}]);
app.start();
</p>