简体   繁体   中英

jquery ui autocomplete: navigating json objects

The excellent answer by Paz got me through a rough patch this week with the autocomplete jQuery UI deal.

All that to say, How does one choose the correct json response if the you have two different "base" objects in your json response.

Simply put, I have a ruby instance variable made up of two models, Pitch and User. I want to autocomplete based on this instance variable. The json response is, say

[{"user":{"id":1,"name":"Blah Hugo"}},
{"user":{"id":3,"name":"Blaz Foobar"}},
{"pitch":{"id":2,"name":"Blasters On Business Apparel"}}]

The autocomplete javascript file looks like this NOW, and it works < snippet only >:

.data( "autocomplete" )._renderItem = function( ul, item ) {
  return jQuery( "<li></li>" )
  .data( "item.autocomplete", item )
  .append( "<a>" + (item.user ? item.user.name : item.pitch.name) + "</a>" )
  .appendTo( ul );
};

Again my problem is this ternary i had to use. item[0].name doesn't work, nor did item.item[0].name Is there no way to get the generic 'user' or 'pitch' if you don't know the name of either?

I'd have though one of them would. What says you?

I don't think there's much wrong with what you have, but maybe a slight improvement would be:

.data("autocomplete")._renderItem = function(ul, item) {
    item = item.user || item.pitch;

    return jQuery("<li></li>")
        .data("item.autocomplete", item)
        .append("<a>" + item.name + "</a>")
        .appendTo(ul);
};

You could try using the || (logical OR) to sort of short hand your ternary operator you have in the .append() method.

Does this do what you want it to?

.data( "autocomplete" )._renderItem = function( ul, item ) {
    item = item.user || item.pitch || {name:""};
    .append( "<a>" + item.name + "</a>" )
    return jQuery( "<li></li>" )
    .data( "item.autocomplete", item )
    .append( "<a>" + item.name  + "</a>" )
    .appendTo( ul );
};

This will return the first "non-false" value in the list of arguments; in this case item.user.name and item.pitch.name . In this case, if your JSON object has a user property, the name value will be returned. If the JSON object has a pitch property, the name value will be returned. If both of those operations return undefined , a blank string will be returned and appended into the a tag.

This answer gives more information about use and special cases to keep in the back of your mind when using using the 'OR' method.

UPDATE : Fixed null exception possibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM