简体   繁体   中英

A DRY solution of JQuery UI Autocomplete for more than one controller?

I have two controllers, each has an autocomplete textbox to search by last name. autocomplete.json.erb is stored in its corresponding view.

This following autocomplete code snippet would work nice for both controllers

  $( ".auto_complete" ).autocomplete({        
        minLength: 2,
        source: 'autocomplete.json'
    });

since these following requests will be generated:

http://localhost:3000/users/autocomplete.json?term=ab
http://localhost:3000/members/autocomplete.json?term=ab

however, if I use REST path, there is no trailing '/' at the end of URL:

members_path: http://localhost:3000/users
users_path: http://localhost:3000/members

So I have to do this:

<%= link_to "Users", users_path+'/' %>

without the '/' at the end, jquery-ui would invoke the following instead:

http://localhost:3000/autocomplete.json?term=ab

This does not seem to me as a clean solution. Another way is to make a separate auto complete code and css class for each controller so that the source attribute can be assigned to a different controller, eg:

source: '/users/autocomplete.json'
source: '/members/autocomplete.json'

Is there a DRY solution to this problem?

Thanks.

You can ask the current url and use it as a prefix

$( ".auto_complete" ).autocomplete({        
    minLength: 2,
    source: window.location.href + '/autocomplete.json'
});

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