what would be an efficient (and userfriendly) way to realize the following in javascript/jQuery?
Depeding on the mime-type of a file, a callback should be executed. The callback is defined by the developer by providing a mime-type description with optional wildcards (e.g. text/javascript, text/*, */*) and the callback itself. There must be a specified order in which the declared types are matched against the given mime-type of the file. For example must text/plain have a higher priority than text/*.
Here some ideas:
Using a simple object
var handler = {
'text/javascript' : callback0,
'text/*' : callback1
}
This would be the most intuitive solution, but the ordering is not guaranteed.
Maintain two lists
var order = ['text/javascript', 'text/*'];
var handler = [callback0, callback1];
This is would be hard to maintain if there are more than two or three types and you are using anonymous functions as callbacks.
Adding an index by wrapping the callback into an object
var handler = {
'text/javascript' : {index: 0, callback0},
'text/*' : {index: 1, callback1}
};
... change thousands of index-properties when inserting an item at the beginning.
Using an array of arrays
var handler = [
['text/javascript', callback0],
['text/*', callback1]
];
This might me more userfriendly than the others, but there is no direct access for known mime-types without iterating over the elements (this would be nice-to-have).
So there are some ways to do the thing I want, but what would be the right way (and why)? Maybe someone has a pattern?
Best,
Hacksteak
I would use the ‘simple object’ solution AND the order array form the ‘maintain two lists’ solution.
Iterate through the order array with a block of code that uses the
handlersimple object to do something that either breaks the loop or continues to the next loop iteration.EDIT TO RESPOND TO A COMMENT
I agree with your comment. I would do something like this to make it just one variable:
Although I would pick better names for the
handlersvariable and/or thehandlers.handlerproperty.ANOTHER RESPONSE TO ANOTHER COMMENT
Maybe you should just modify
handlers.handlerandhandlers.orderone-mime-type-at-a-time:That method fills a little repetitive, but should be easy to maintain in the future. If you want, you can write a function that adds a new property to
handlers.handlerand appends a new mime-type tohandlers.order.