2012-05-31 112 views
0

未定义我有这样的片段:数据( '自动完成')中的CoffeeScript

$("#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 

有时我得到这个错误:未定义

所以

无法设置属性 '_renderItem' 我假设,当:

$("#select_sourcer").autocomplete(...).data("autocomplete") 

是未定义的,我们不能设置属性。正如本文所讨论的:Why am I getting this JS error?

但是,我将如何检查Coffeescript中的投票答案?

+0

为什么不直接设置_renderitem属性,而不是每个.data()? – Bergi

+0

因为它是自动完成链的一部分?我不明白你会怎么做... –

+0

我的意思是,在选项对象中,你启动autocmplete?在检查一些源代码后,我认为它会起作用 – Bergi

回答

2

您可以使用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.

所以,如果你正在运行jQuery和你不能确定是否有DOM中的#select_sourcer,那么你可以只溜?进入正确的地方:

$("#select_sourcer").autocomplete(
    ... 
).data("autocomplete")?._renderItem = (ul, item) -> 
    #-------------------^ 
    ... 

这将有或多或少的效果相同:

x = $('#select_sourcer').autocomplete(...).data('autocomplete') 
if(x) 
    x._renderItem = (ul, item) -> ... 

以上仅用于说明目的,?.实际检查!= null而不是一般的谬误。

这应该只是必要的,如果没有在DOM没有#select_sourcer,所以你可能要避免试图将autocompleter完全绑定,如果你不需要它; OTOH,有时更容易不在乎它是否在那里并且束缚住。

+0

谢谢,谢谢,谢谢。这已经澄清了很多。 –