Skip to content

Instantly share code, notes, and snippets.

@bolshchikov
Created November 7, 2013 22:54
Show Gist options
  • Save bolshchikov/7363304 to your computer and use it in GitHub Desktop.
Save bolshchikov/7363304 to your computer and use it in GitHub Desktop.
Ember SelectionMixin
var SelectionMixin = Ember.Mixin.create({
init: function() {
this.get(this.get('itemClassName')).reopen({
classNameBindings: ['isSelected:selected'],
isSelected: false,
click: function(ev) {
ev.stopImmediatePropagation();
this.get('parentView').handleSelection(ev, this);
}
});
this.set('selected', Ember.A([]));
return this._super();
},
itemClassName: 'itemViewClass',
addSelected: function(itemView) {
if (this.get('selected').indexOf(itemView) === -1) {
itemView.set('isSelected', true);
this.get('selected').pushObject(itemView);
}
},
clearSelection: function() {
var item;
while (this.get('selected.length') !== 0) {
item = this.get('selected').popObject();
item.set('isSelected', false);
}
},
handleSelection: function(ev, itemView) {
// if non of the ctrl, meta, and shift keys
// are pressed, clear the selection
if (!ev.ctrlKey && !ev.metaKey && !ev.shiftKey) {
this.clearSelection();
}
// if selection is performed with shift key
// the selected items should be between the last
// and currently clicked items
if (ev.shiftKey) {
var lastSelected = this.get('selected.lastObject'),
lastSelectedIndex = this.get('content').indexOf(lastSelected.get('content')),
itemViewIndex = this.get('content').indexOf(itemView.get('content')),
minIndex = Math.min(lastSelectedIndex, itemViewIndex),
maxIndex = Math.max(lastSelectedIndex, itemViewIndex),
childViews = this.get('childViews');
this.clearSelection();
for (var i = minIndex; i <= maxIndex; i += 1) {
this.addSelected(childViews[i]);
}
}
this.addSelected(itemView);
},
click: function() {
this.clearSelection();
},
keyPress: function(ev) {
if (ev.keyCode === 65 && ev.shiftKey) {
this.get('childViews').forEach(function(itemView) {
this.addSelected(itemView);
}, this);
}
}
});
Ember.CollectionView.extend(SelectionMixin, {
tagName: 'ul',
attributeBindings: ['tabIndex'],
tabIndex: -1
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment