javascript - Coffeescript/jQuery Pattern: Caching Data Across Events -


i have list of items abstracts, , can made expand via ajax on click. i'v written following code in coffeescript:

current_open_row = null  $('li.faq-item').live 'click', (event) ->   $.post("/faqs/update_rows", {old_row_id: current_open_row, new_row_id: $(this).attr('id')}, (data) ->     replace_items data   , 'json')   current_open_row = $(this).attr('id') 

this doesn't read smooth coffeescript , find myself thinking, "what have done better," in particular, instantiating current_open_row variable outside scope of click handler feels strange. not doing this, of course, causes new instantiation upon entry handler, undefined.

other refactoring $(this).attr('id') variable, there jumps out ugly, suboptimal, unreadable, etc., or pretty way of it?

thanks!

well, first off, think you'll find switching camelcase eventually... know many people prefer readability_of_underscores, every library interact (including jquery) uses camelcase. keep in mind.

setting aside, issue of having scope variables = null one. i've tried persuade jeremy there should nicer scoping syntax, he's firmly against it. i'd suggest moving variable object property. fortunately, jquery, there plenty of places stick data. how using list's .data method? has additional advantage: if want on multiple lists in future (with 1 current_open_row in each list), won't have change code 1 bit. add more lists .faq-item children markup.

one more minor point: give post call callback

(data) -> replace_items data 

if that's you're doing, why not pass replace_items directly? :)

i'd put each argument post function on own line readability. key-value pairs automatically combined single object, without curly braces. here's how looks:

$('li.faq-item').live 'click', (event) ->   $row = $(this)   $list = $row.parent()   row_id = $row.attr 'id'    $.post(     "/faqs/update_rows",     old_row_id: $list.data('current_open_row'),     new_row_id: row_id,     replace_items,     'json'   )    $list.data 'current_open_row', row_id 

Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -