[英]data('autocomplete') is undefined in Coffeescript
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 无法设置未定义的属性'_renderItem'
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? 正如在这个帖子中所说: 为什么我得到这个JS错误?
But, how would I do that checking of the voted answer in Coffeescript? 但是,我如何检查Coffeescript中的投票答案呢?
You could use the accessor variant of the existential operator : 您可以使用存在运算符的访问器变体 :
The accessor variant of the existential operator
?.
存在运算符的存取变体?.
can be used to soak up null references in a chain of properties. 可用于在属性链中吸收空引用。 Use it instead of the dot accessor.
使用它代替点访问器.
in cases where the base value may be null or undefined . 在基值可能为null或未定义的情况下 。
So, if you're running that jQuery and you're not certain that you have a #select_sourcer
in the DOM, then you could just slip a ?
所以,如果你正在运行那个jQuery并且你不确定你在DOM中有#select_sourcer
,那么你可以放一个?
into the right place: 进入正确的地方:
$("#select_sourcer").autocomplete(
...
).data("autocomplete")?._renderItem = (ul, item) ->
#-------------------^
...
That will have more or less the same effect as: 这将具有或多或少相同的效果:
x = $('#select_sourcer').autocomplete(...).data('autocomplete')
if(x)
x._renderItem = (ul, item) -> ...
The above is just for illustrative purposes, ?.
以上仅用于说明目的, ?.
actually checks != null
rather than general falsiness. 实际上检查!= null
而不是一般的虚假。
This should only be necessary if there is no #select_sourcer
in the DOM so you might want to avoid attempting to bind the autocompleter altogether if you don't need it; 只有在DOM中没有#select_sourcer
时才需#select_sourcer
,所以如果你不需要它,你可能想要避免尝试完全绑定自动完成器; OTOH, sometimes it is easier to not care if it is there or not and bind away. OTOH,有时更容易不在乎它是否存在并且结合在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.