I am writing java/spring webapp in which every user can have its own word list. Every time when user adds/removes a word then there is a ajax call which sends a JSON with this word to add/delete and when server side is done then there is returned current word list in JSON object to jQuery.
Everything is working ok. For small JSON word list adding and removing is very fast but when word list is getting bigger then ajax calls becomes slower. And adding/removing calls will be very frequent.
Example of JSON word list [polish words]:
[{"word":"abrys","wordId":646},{"word":"acpan","wordId":647},
{"word":"akrania","wordId":457},{"word":"akwawita","wordId":648},
{"word":"amalgamat","wordId":399},{"word":"amurski","wordId":465},
{"word":"amurskie","wordId":1030},{"word":"ananke","wordId":649},
{"word":"androlog","wordId":650}]
jQuery [more or less]:
$("#add_word_submit").live("click", function(e) {
e.preventDefault();
var word = $('#add_word').serializeObject();
$.postJSON("word.html", word, function(words) {
showDividedAccountWords(words);
});
});
$(".delete_button").live("click", function(e) {
e.preventDefault();
if(confirm(Main.confirmWordDelete)) {
var wordId = $(this).attr("id").substring("delete_".length);
wordName["word"] = $(this).children("img").attr("alt");
$.ajax({
type: "DELETE",
url: "word/" + wordId + ".html",
success: function(words) {
showDividedAccountWords(words);
}
});
}
});
Java/Spring:
@RequestMapping(value="/word", method = RequestMethod.POST)
public @ResponseBody List<Word> addNewWord(@RequestBody Word word, Principal principal) {
wordService.addNewWord(word, principal.getName());
return getCurrentWords(principal.getName());
}
@RequestMapping(value="/word/{wordId}", method = RequestMethod.DELETE)
public @ResponseBody List<Word> deleteWord(@PathVariable Long wordId, Principal principal) {
wordService.deleteWord(wordId, principal.getName());
return getCurrentWords(principal.getName());
}
public List<Word> getCurrentWords(String username) {
List<Word> accountWords = new ArrayList<Word>();
accountWords.addAll(wordService.listUserWords(username));
return accountWords;
}
Could you please give me some hints to refactor it? Maybe i shouldn’t return a current word list every time user add/removes word?
To incrementally add word objects to the list, pass the new word to the server and have it return just a single (word:wordid) object. You can then add it to the existing list and sort it as follows: