Published 14/08/2016
Last Updated 20/11/2024

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