Building out a mini-framework with CoffeeScript
A portion of the application I'm working on has a comments page with a form at top to add new comments and a list of comments beneath it. I've been working on using CoffeeScript classes to represent my DB models, as per this episode on using data-behaviors
I started breaking my CoffeeScript classes up into separate classes to mirror my Rails controller actions:
class Comments.New...
class Comments.Create...
class Comments.Update...
Since I'm using server-generated JS, my Rails actions correspond to the class:
# app/views/comments/create.js.erb
new Comments.Create("<%=j render(partial: 'comment', locals: { comment: @comment }) %>");
# comments/create.coffee
class Comments.Create
constructor: (comment) ->
@comment = $(comment)
@newForm = $("[data-behavior='new-comment-form']")
@comments = $("[data-behavior='comments']")
@addComment()
@resetForm()
addComment: () ->
@comments.prepend(@comment)
resetForm: () ->
@newForm[0].reset()
The comment
partial has enough data attributes to allow my CoffeeScript code to know what to do with it.
To initialize on page load, I have a global.coffee
that starts all my major events:
# global.coffee
$(document).on "turbolinks:load", ->
$.map $("[data-behavior='new-comment-form']"), (element, index) ->
new Comments.New(element)
I probably spend 75% of my time building out front-end interfaces, and technically I'm a "back-end" guy :)p I just hate a lot of the bloat/unused portions of some of the really large frameworks out there.
I'm puzzling over if this is a good approach, or how others solve similar problems? I'm finding that I want to run a decent amount of JS/CoffeeScript code for each of my corresponding Rails actions.
A lot of deciding to do it yourself or to use a frontend framework is going to come down to the problems you're trying to solve. You get both the client side changes and the server side rendering that's good for SEO in one fell swoop here. A frontend framework adds a lot of complexity, but depending on what you're trying to do, it can be there either approach.
So what are some things that are your most complex bits to implement client side?