JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<div class="test-class">
<h1>Backbone and jQuery sortable - test</h1>
<div id="items-collection-warper"></div>
</div>
CSS
.test-class{
font-family: Arial;
}
.test-class li{
list-style:none;
height:20px;
}
.test-class h1{
font-size: 12px;
}
.ui-sortable-helper{
opacity:0.4;
}
.sortable-placeholder{
background: #ddd;
border:1px dotted #ccc;
}
JavaScript
$(document).ready(function(){
var collection = [
{name: "Item ", order: 0},
{name: "Item 1", order: 1},
{name: "Item 2", order: 2},
{name: "Item 3", order: 3},
{name: "Item 4", order: 4}
];
var app = {};
app.Item = Backbone.Model.extend({});
app.Items = Backbone.Collection.extend({
model: app.Item,
comparator: 'order',
});
app.ItemView = Backbone.View.extend({
tagName: 'li',
template: _.template('<span><%= name %> - <b><%= order %></b></span>'),
initialize: function(){
},
render: function(){
var oneItem = this.$el.html(this.template(this.model.attributes));
return this;
}
});
app.AppView = Backbone.View.extend({
el: "#items-collection-warper",
tagName: 'ul',
viewItems: [],
events:{
'listupdate': 'listUpdate'
},
initialize: function(){
var that = this;
this.$el.sortable({
placeholder: "sortable-placeholder",
update: function(ev, ui){
that.listUpdate();
}
});
},
render: function(){
var that= this;
this.collection.each(function(item){
that.viewItems.push(that.addOneItem(item));
return this;
});
},
addOneItem: function(item){
var itemView = new app.ItemView({model: item});
this.$el.append(itemView.render().el);
return itemView;
},
listUpdate: function(){
_.each(this.viewItems, function(item){
item.model.set('order', item.$el.index());
});
this.collection.sort({silent: true})
_.invoke(this.viewItems, 'remove');
...