Skip to content

Instantly share code, notes, and snippets.

@tbbooher
Created August 28, 2015 00:32
Show Gist options
  • Save tbbooher/dc8601eae811e18cf3e3 to your computer and use it in GitHub Desktop.
Save tbbooher/dc8601eae811e18cf3e3 to your computer and use it in GitHub Desktop.
var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
$(function() {
var names, user_id;
if ($('#new_journal_entry').length) {
console.log('going for it');
user_id = $('#journal_entry_friend_ids').data('user');
console.log("kicking things off with " + user_id);
names = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: "/users/" + user_id + "/friends.json",
transform: function(response) {
console.log('transform', response);
return {
value: response.id,
label: response.name
};
}
}
});
names.initialize();
return $('.tokenfield').on('tokenfield:createtoken', function(event) {
var current_value, existingTokens, name_array;
user_id = $('#journal_entry_friend_ids').data('user');
console.log("token created: starting with " + user_id);
name_array = name_array = $.map(names.index.datums, function(e) {
return e.name;
});
current_value = event.attrs.value;
existingTokens = $(this).tokenfield('getTokens');
$.each(existingTokens, function(index, token) {
if (token.value === current_value) {
event.preventDefault();
}
});
if (indexOf.call(name_array, current_value) < 0) {
console.log('new token');
console.log(user_id);
console.log('token: ' + event.attrs.value + 'must be created.');
$.ajax({
type: "POST",
url: '/users/' + user_id + '/friends',
data: {
friend: {
name: current_value
}
},
success: function(data) {
console.log('creation successful');
$('#journal_entry_friend_ids').closest('.form-group').addClass('has-error');
return $('#journal_entry_friend_ids').closest('.form-group').append('<p>added friend:' + current_value + '</p>');
},
error: function(data) {
return false;
}
});
}
}).on('tokenfield:removetoken', function(event) {
return console.log('token removed');
}).on('tokenfield:edittoken', function(event) {
return console.log('token edited');
}).tokenfield({
typeahead: [
null, {
source: names.ttAdapter(),
display: 'name',
name: 'friends-names'
}
]
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment