I am using Kendoui uploaded for async uploads on my site.
A little feature I have is that when an image upload completes, a small thumbnail is created and a preview appears on the page:
...
success: function(e)
{
if(e.operation == 'upload')
{
$('#previews').append('<img src="'+ROOT+'cakes/'+e.files[0].name+'"/>');
}
else if(e.operation == 'remove')
{
$('#previews img[src="'+ROOT+'cakes/'+e.files[0].name+'"]').remove();
}
...
As you can see, I am matching against the img src attribute which I feel may be slow and inefficient. Is there a better way to achieve what I am trying?
First off, if your current code is working, then there's really no need to change it unless you actually have a performance problem. Modern computers/phones are so darn fast these days that you really only ought to spend time on a performance issue when you actually have a performance issue. Otherwise your time would be better spent improving your app/page in other ways.
That said, looking something up by id is a lot faster than looking up most other ways (and certainly faster than looking up by an attribute like src
. You could coin a unique id from the filename like this, assign it to the image when you create it and then use it to find the image to remove it:
success: function(e)
{
var name = "img_" + e.files[0].name.replace(/[.\/ ]/, "_");
if (e.operation == 'upload')
{
$('#previews').append('<img id="' + name + '" src="'+ROOT+'cakes/'+e.files[0].name+'"/>');
}
else if(e.operation == 'remove')
{
$('#' + name).remove();
}
...