I have a coffescript datastructure which consists of an object which has arrays of other objects, these objects have helper methods which make it easier to manipulate the data in the data structure:
class CrossData
species_list: {
species1: [21,10,30,40]
}
constructor: () ->
@species = "defualt"
@donors = [new CrossDonor] #array that will be full of CrossDonors
helper_method: (arg1) =>
#do stuff with crossdata
class CrossDonor
constructor: () ->
@name = "default"
@linkage_group = -1
@trait_cm = -1
helper_method: (arg1) ->
#do stuff with cross donor
cross_data = new CrossData
if I try and upload this via jquery ajax ie:
$.ajaxSetup(
beforeSend: (xhr) ->
xhr.setRequestHeader('X-CSRF-Token',
$('meta[name="csrf-token"]').attr('content')))
$.ajax(
type: "POST",
url: '/crosses/save',
data: cross_data
contentType: 'json'
success: (msg) ->
alert( "Data Saved: " + msg )
)
it doesn’t work since it trips up over the functions, I guess the answer is to create a function which produces a json verison of the coffee script classes. I’m wondering if there is a jquery plugin which will give me a coffee_class data type?
One thing you could do that might help you in the future would be to add a
toJSONmethod:This is more or less like
to_jsonin Rails. jQuery won’t call it automatically, unfortunately, but the JSON library will and so will Backbone (if you end up using Backbone); adding atoJSONmethod also allows the object to control its own serialization.Then add a
toJSONcall to your$.ajax:Or, with recent jQuery’s, you could set up an AJAX pre-filter to automatically call
toJSONwhen it is available:Then if you called
$.ajaxwith adatathat had atoJSONmethod,toJSONwould get called to serialize thedataobject.You could also set up a simple recursive
$.ajaxPrefilterto automatically skip over anything inoriginal_opts.datathat$.isFunctiondetected as a function. You’d want to use$.isPlainObjectto skip overdatathat is already a string though.I don’t know of any plugins that do this automatically though.