August Rails and JS notes


This month I have been pretty busy with lots of tasks, mainly on frontend with JS. These notes are from exprerience executing those tasks.

Using namespace in JS

Creating too manly JS functions may cause name collision and pollute global namespace. When a project is going to have too many JS, it is better to group functions into namespaces for better maintenance.

window.Foo =
  bar: () ->
    // do something

  qux: () ->
    // do something else

So we will have 2 functions with namespace: Foo.bar() and Foo.qux()

There is a caveat: the following code does not work

window.Foo =
  bar: () ->
    qux()

  qux: () ->
    // do something else

This is because JS function call look for global namespace, so refer qux() means looking for global function qux() which is undefined, not the Foo.qux().

This Stackoverflow question discusses solutions around this. There are a few different solutions but the clearest and easiest one is:

window.Foo =
  bar: () ->
    Foo.qux()

  qux: () ->
    // do something else

jQuery .off()

http://api.jquery.com/off/

I guess this is basic knowledge but I've just happened to know: if a webpage is not reloaded, all bindings of an element are kept. This may cause surprise behaviours such as repetitive output.

The solution to this is to make sure calling .off() function to unbind all previous bindings before trigger new event.

$(el).off().on 'click' ->
  // do something

Multiple ajax image uploads

So the upload process is handled by Carrierwave and Dropzone. No big deal!

The issue comes when the requirements state that: "in new product form, upload images by ajax immediately after being selected". With Rails accept_nested_attributes we could solve this issue using AJAX for uploading then inject JSON response into nested attribute fields. I dislike this solution since the uploaded images initially has no parent (product_id is nil) so I use another approach by using dummy parent for those uploaded images then reassign their parent to the product when it is saved.

Sortable

There are few things that require drag and drop sorting: galleries, tasks lists, etc.

Many JS lib solve this. Most common one is jQueryUI which is a popular extension of jQuery. But the drag and drop function of jQuery does not look smoothly. I prefer to look for an alternative.

After finding and testing some drag and drop JS lib, Sortable is the best so far:

  • Does not depend on jQuery
  • Smoothy drag and drop experience
  • Simple API
  • Easily integrate with React, Angular, Meteor, Knockout, Polymer which is a big plus

Next month

I've done some work with React but my knowledge with React is very limited. I would like to explore into React world to learn more. My next month note will probably focus on React.