I have this snippet:
$("#select_sourcer").autocomplete(
minLength: 2
source: "/admin/users/list_of_sourcers.json"
focus: (event,ui) ->
$('#select_sourcer').val(ui.item.full_name)
false
select: (event,ui) ->
$("#select_sourcer").val(ui.item.full_name)
$("#merchant_sourcer_id").val(ui.item.id)
false
).data("autocomplete")._renderItem = (ul, item) ->
$("<li></li>").data("item.autocomplete", item).append("<a>" + item.full_name_with_status + "</a>").appendTo ul
And sometimes I get this error:
Cannot set property ‘_renderItem’ of undefined
So I am assuming, that when:
$("#select_sourcer").autocomplete(...).data("autocomplete")
Is undefined, we can’t set the attribute. As talked in this thread: Why am I getting this JS error?
But, how would I do that checking of the voted answer in Coffeescript?
You could use the accessor variant of the existential operator:
So, if you’re running that jQuery and you’re not certain that you have a
#select_sourcerin the DOM, then you could just slip a?into the right place:That will have more or less the same effect as:
The above is just for illustrative purposes,
?.actually checks!= nullrather than general falsiness.This should only be necessary if there is no
#select_sourcerin the DOM so you might want to avoid attempting to bind the autocompleter altogether if you don’t need it; OTOH, sometimes it is easier to not care if it is there or not and bind away.