For a practical example we need to start with some assumptions: You have a new mobile project that communicates with a RESTful server API. After a few weeks of development some project requirements change and now every ajax url must start with
- You don’t want to manually find every ajax call in the project and prepend the url strings with
- You don’t want to force your team to remember to do this as you develop.
- You want to implement this new requirement as seamlessly as possible.
jQuery’s powerful ajax methods are well known, but let’s say you’re working with a more simplified library like Zepto.js which was built for mobile. Middleman.js can solve this problem with just a few lines:
You can call
$.ajax as you normally would. The filter method will be executed first, and the array
args that is returned by the filter method will be passed to the original
$.ajax method as parameters.
ajaxSettings variable after I’ve modified it’s
url property. See this for more details.
In the previous example, Middleman will use the
lib object for context when executing the ajax method (in this case Zepto.js). However, Middleman can also take an optional
context parameter that will be used instead, like this:
Notice that the context of the
stringify method became
Array. Had I passed
context : Object, instead, the output would have been
[object Array] instead of
a,b,c,d. You’ve probably seen this kind of behavior in other popular libraries like Underscore.js’s
Currently there is no way to disable Middleman’s meddling once you’ve called the map function. We’re planning to incorporate an internal registery in a future release that will allow you to inspect the Middleman object to see what methods have been overloaded, and also make it easy for Middleman to flip it’s filters on or off at a granular level.
- Repository - Middleman.js
- License - MIT