Created
April 25, 2014 06:01
-
-
Save krisselden/11279071 to your computer and use it in GitHub Desktop.
sortable-list component example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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