Skip to content

Commit

Permalink
For <Carousel>, set direction on event
Browse files Browse the repository at this point in the history
  • Loading branch information
taion committed Apr 10, 2016
1 parent a865161 commit ed4ee10
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 7 deletions.
6 changes: 3 additions & 3 deletions docs/examples/CarouselControlled.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ const ControlledCarousel = React.createClass({
};
},

handleSelect(selectedIndex, e, selectedDirection) {
alert('selected=' + selectedIndex + ', direction=' + selectedDirection);
handleSelect(selectedIndex, e) {
alert('selected=' + selectedIndex + ', direction=' + e.direction);
this.setState({
index: selectedIndex,
direction: selectedDirection
direction: e.direction
});
},

Expand Down
17 changes: 15 additions & 2 deletions src/Carousel.js
Original file line number Diff line number Diff line change
Expand Up @@ -282,8 +282,21 @@ let Carousel = React.createClass({
let previousActiveIndex = this.getActiveIndex();
direction = direction || this.getDirection(previousActiveIndex, index);

if (this.props.onSelect) {
this.props.onSelect(index, e, direction);
const { onSelect } = this.props;

if (onSelect) {
if (onSelect.length > 1) {
// React SyntheticEvents are pooled, so we need to remove this event
// from the pool to add a custom property. To avoid unnecessarily
// removing objects from the pool, only do this when the listener
// actually wants the event.
e.persist();
e.direction = direction;

onSelect(index, e);
} else {
onSelect(index);
}
}

if (this.props.activeIndex == null && index !== previousActiveIndex) {
Expand Down
32 changes: 30 additions & 2 deletions test/CarouselSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,36 @@ describe('Carousel', () => {
});

it('Should call onSelect when indicator selected', (done) => {
function onSelect(index) {
assert.equal(index, 0);
function onSelect(index, ...args) {
expect(index).to.equal(0);

// By using rest arguments here, we can avoid triggering the logic to
// persist and decorate the event.
const [event] = args;
expect(event).to.not.exist;

done();
}

let instance = ReactTestUtils.renderIntoDocument(
<Carousel activeIndex={1} onSelect={onSelect}>
<Carousel.Item ref="item1">Item 1 content</Carousel.Item>
<Carousel.Item ref="item2">Item 2 content</Carousel.Item>
</Carousel>
);

ReactTestUtils.Simulate.click(
ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'carousel-indicators')
.getElementsByTagName('li')[0]
);
});

it('Should call onSelect with direction', (done) => {
function onSelect(index, event) {
expect(index).to.equal(0);
expect(event.direction).to.equal('prev');
expect(event.isPersistent()).to.be.true;

done();
}

Expand Down

0 comments on commit ed4ee10

Please sign in to comment.