Last active
March 14, 2022 17:52
-
-
Save Killavus/13676d46afab12e81f7d to your computer and use it in GitHub Desktop.
Example of possible refactoring of badly written code - loading photos and making it grayed after click
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
Photos = {} | |
class Photos.App | |
constructor: -> | |
@gui = new Photos.Gui($("#photos-list")) | |
@backend = new Photos.Backend() | |
start: => | |
@backend.fetchPhotos() | |
.done( | |
(photos) => | |
for photo in photos | |
@gui.addPhoto(photo) | |
) | |
.fail(@gui.fetchPhotosFailed) | |
class Photos.Gui | |
constructor: (@dom) -> | |
photoRow: (photo) => | |
$("<li><a id='photo_#{photo.id}' href='#{photo.url}'><img src='#{photo.url}' alt='#{photo.alt}' /></a></li>") | |
addPhoto: (photo) => | |
photoNode = @photoRow(photo).appendTo(@dom) | |
@linkClickHandlerToPhoto(photoNode, photo) | |
linkClickHandlerToPhoto: (photoNode, photo) => | |
photoNode.on('click', (e) => | |
e.preventDefault() | |
@switchPhotoToGrayscaled(photoNode, photo) | |
switchPhotoToGrayscaled: (photoNode, photo) => | |
photoNode.find('img').prop('src', photo.grayscaledURL()) | |
fetchPhotosFailed: => | |
$("<li>Failed to fetch photos.</li>").appendTo(@dom) | |
class Photos.Photo | |
constructor: (@id, @url, @alt) -> | |
grayscaledURL: => | |
@url + ".grayscaled.jpg" | |
@fromJSON: (json) -> | |
new Photos.Photo(json.id, json.url, json.alt) | |
class Photos.Backend | |
fetchPhotos: => | |
request = $.ajax( | |
url: '/photos' | |
type: 'GET' | |
contentType: 'application/json' | |
) | |
.then (response) => | |
photos = [] | |
for photo in response.photos | |
photos.append(Photos.Photo.fromJSON(photo)) | |
photos | |
$(document).ready => | |
# put logic about starting your app here. | |
app = new Photos.App() | |
app.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment