Commit 163908b393bf69e4accbe22cbba1df50fa491649
1 parent
1bba46d6
Exists in
master
and in
4 other branches
user select2 javascript
Showing
1 changed file
with
47 additions
and
0 deletions
Show diff stats
| @@ -0,0 +1,47 @@ | @@ -0,0 +1,47 @@ | ||
| 1 | +$ -> | ||
| 2 | + userFormatResult = (user) -> | ||
| 3 | + avatar = gon.gravatar_url | ||
| 4 | + avatar = avatar.replace('%{hash}', md5(user.email)) | ||
| 5 | + avatar = avatar.replace('%{size}', '24') | ||
| 6 | + | ||
| 7 | + markup = "<div class='user-result'>" | ||
| 8 | + markup += "<div class='user-image'><img class='avatar s24' src='" + avatar + "'></div>" | ||
| 9 | + markup += "<div class='user-name'>" + user.name + "</div>" | ||
| 10 | + markup += "<div class='user-username'>" + user.username + "</div>" | ||
| 11 | + markup += "</div>" | ||
| 12 | + markup | ||
| 13 | + | ||
| 14 | + | ||
| 15 | + $('.ajax-users-select').select2 | ||
| 16 | + placeholder: "Search for a user" | ||
| 17 | + minimumInputLength: 0 | ||
| 18 | + ajax: # instead of writing the function to execute the request we use Select2's convenient helper | ||
| 19 | + url: "/api/v3/users.json" | ||
| 20 | + dataType: "json" | ||
| 21 | + data: (term, page) -> | ||
| 22 | + search: term # search term | ||
| 23 | + per_page: 10 | ||
| 24 | + private_token: gon.api_token | ||
| 25 | + | ||
| 26 | + results: (data, page) -> # parse the results into the format expected by Select2. | ||
| 27 | + # since we are using custom formatting functions we do not need to alter remote JSON data | ||
| 28 | + results: data | ||
| 29 | + | ||
| 30 | + initSelection: (element, callback) -> | ||
| 31 | + id = $(element).val() | ||
| 32 | + if id isnt "" | ||
| 33 | + $.ajax("http://api.rottentomatoes.com/api/public/v1.0/users/" + id + ".json", | ||
| 34 | + data: | ||
| 35 | + apikey: "ju6z9mjyajq2djue3gbvv26t" | ||
| 36 | + | ||
| 37 | + dataType: "jsonp" | ||
| 38 | + ).done (data) -> | ||
| 39 | + callback data | ||
| 40 | + | ||
| 41 | + | ||
| 42 | + formatResult: userFormatResult # omitted for brevity, see the source of this page | ||
| 43 | + #formatSelection: userFormatSelection # omitted for brevity, see the source of this page | ||
| 44 | + dropdownCssClass: "ajax-users-dropdown" # apply css that makes the dropdown taller | ||
| 45 | + escapeMarkup: (m) -> # we do not want to escape markup since we are displaying html in results | ||
| 46 | + m | ||
| 47 | + |