Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSauli Laitinen
5,992 PointsIs there an alternative way to "chaining"?
Hi,
In this exercise many things are chained(?) together. What I mean that the mosuedown is followed with mousemove, mouseup and mouseleave all in one line or statement.
I was wondering that would there have been an alternative way of writing all of this? I mean that could the mousedown, mousemove, mouseup and mouseleave have been separated to separate statements?
$canvas.mousedown(function(e){
lastEvent = e;
mouseDown = true;
}).mousemove(function(e){
if(mouseDown === true) {
context.beginPath();
context.moveTo(lastEvent.offsetX, lastEvent.offsetY);
context.lineTo(e.offsetX, e.offsetY);
context.strokeStyle = color;
context.stroke();
lastEvent = e;
}
}).mouseup(function(){
mouseDown = false;
}).mouseleave(function(){
$canvas.mouseup();
});
3 Answers
Ryan Boone
26,518 PointsYes, you would just split out the mouse events and begin each command with $canvas, like so:
$canvas.mousedown(function(e){
lastEvent = e;
mouseDown = true;
});
$canvas.mousemove(function(e){
if(mouseDown === true) {
context.beginPath();
context.moveTo(lastEvent.offsetX, lastEvent.offsetY);
context.lineTo(e.offsetX, e.offsetY);
context.strokeStyle = color;
context.stroke();
lastEvent = e;
}
});
$canvas.mouseup(function(){
mouseDown = false;
});
$canvas.mouseleave(function(){
$canvas.mouseup();
});
Steven Walters
10,573 PointsDoesn't it make sense to chain in this case because it's all one action.
Sauli Laitinen
5,992 PointsOk, thanks.
Samuel Rueby
22,538 PointsSamuel Rueby
22,538 PointsYup, chaining can be beneficial but it's not required.