Skip to content

Instantly share code, notes, and snippets.

@krisselden
Created April 25, 2014 06:01
Show Gist options
  • Save krisselden/11279071 to your computer and use it in GitHub Desktop.
Save krisselden/11279071 to your computer and use it in GitHub Desktop.
sortable-list component example
{{#each fruits}}
{{this}}
{{/each}}
{{draggable-list values=fruits}}
var IndexRoute = Ember.Route.extend({
model: function() {
var model = {
fruits: ['apple','pear','banana','kiwi']
};
setTimeout(function () {
model.fruits.pushObject('orange');
model.fruits.removeObject('pear');
}, 2000);
return model;
}
});
export default IndexRoute;
function applySortable(el, target, method) {
if (el) {
el.sortable().bind('sortupdate', function(e, ui) {
Ember.run(target, method, ui.item.text(), ui.item.index());
});
}
}
function destroySortable(el) {
if (el) {
el.sortable('destroy');
}
}
var DraggableListComponent = Ember.Component.extend({
values: null,
tagName: 'ul',
render: function (buffer) {
var values = this.get('values');
if (values) {
values.forEach(function (value) {
buffer.push('<li>'+value+'</li>');
});
}
},
didInsertElement: function () {
applySortable(this.$(), this, 'itemDragged');
},
willDestroyElement: function () {
destroySortable(this.$());
},
itemDragged: function (value, index) {
var values = this.get('values');
this.updateDisabled = true;
values.removeObject(value);
values.insertAt(index, value);
this.updateDisabled = false;
},
valuesWillChange: function () {
var values = this.get('values');
if (values) {
values.removeArrayObserver(this);
}
}.observesBefore('values'),
valuesDidChange: function () {
var values = this.get('values');
if (values) {
values.addArrayObserver(this);
}
}.observes('values').on('init'),
arrayWillChange: function (values, start, removeCount, addCount) {
if (this.updateDisabled) return;
var ul = this.$();
if (ul) {
ul.sortable('destroy');
ul.find('li').slice(start, start+removeCount).remove();
}
}.on('values'),
arrayDidChange: function (values, start, removeCount, addCount) {
if (this.updateDisabled) return;
var ul = this.$();
if (ul) {
values.slice(start, start+addCount).forEach(function (value) {
$('<li></li>').text(value).appendTo(ul);
});
applySortable(ul, this, 'itemDragged');
}
}
});
export default DraggableListComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment