Skip to content

Instantly share code, notes, and snippets.

@roman-manchenko
Created February 7, 2013 10:35
Show Gist options
  • Save roman-manchenko/4730155 to your computer and use it in GitHub Desktop.
Save roman-manchenko/4730155 to your computer and use it in GitHub Desktop.
/**
* cover_cards view for touch devices
*/
define(['jquery', 'backbone', 'widgets/templates/cover_cards', 'widgets/views/cover_card', 'libs/jquery/plugins/jquery.hammer'], function ($, BB, Template, CoverCardView) {
return BB.View.extend({
events: {
'drag': 'onDrag',
'dragend': 'onDragEnd'
},
initialize: function () {
this._tmpl = this.options.template || Template;
this.collection = this.options.collection;
this.activeId = this.options.activeId;
this.currentIndex = 0;
this.totalCards = 0;
},
renderCards: function() {
var $wrap = this.$('.cover-card-items'),
$overview = this.$('.cover-cards-overview ul');
this.initIndex = 0;
for (var i = 0, len = this.collection.length; i < len; i++) {
var model = this.collection.at(i);
if (model.get('post') && (model.get('post')['headline'] || model.get('post')['image210x'] || model.get('post')['slide_210x'])) {
var coverCardView = this.makeInstance(CoverCardView, {model: this.collection.at(i)}).render();
$wrap.append(coverCardView.el);
this.watchEvent(coverCardView, 'close', 'onItemClose', this);
var $li = $('<li>').text(model.get('id'));
this.activeId === model.get('id') && (this.initIndex = this.totalCards);
$overview.append($li);
this.totalCards++;
}
}
this.slideTo(this.initIndex);
},
onItemClose: function(e) {
this.trigger('item_close');
},
onDrag: function(e) {
var left = 0;
if (e.direction === 'left') {
left = 0 - e.distance;
} else if (e.direction === 'right') {
left = e.distance;
}
this.$('.cover-card-items').css({marginLeft: left});
},
onDragEnd: function(e) {
this.$('.cover-card-items').css({marginLeft: 0});
// if we moved the slide 50px then navigate
if(Math.abs(e.distance) > 50) {
if(e.direction == 'right') {
this.prev();
} else if(e.direction == 'left') {
this.next();
}
}
},
slideTo: function(index) {
if (index > this.totalCards-1) {
index = this.totalCards-1;
} else if (index < 0) {
index = 0;
}
this.$('.cover-card-items').css({left: 0 - (this.coverWidth * index)});
this.currentIndex = index;
this.updateOverView();
},
next: function() {
this.slideTo(this.currentIndex+1);
},
prev: function() {
this.slideTo(this.currentIndex-1);
},
updateOverView: function() {
var $overview = this.$('.cover-cards-overview li').removeClass('active');
$($overview.get(this.currentIndex)).addClass('active');
},
render: function () {
this.$el.html(this._tmpl.render());
this.coverWidth = this.$('.cover-cards').width();
this.renderCards();
this.$('.cover-cards').hammer();
return this;
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment