How to achieve library-agnosticism when building a javascript framework? - javascript

I've started looking into architecturing a javascript framework.
I don't want to reinvent the wheel here, especially regarding browser quirks, and know that for that matter, I'll have to rely, at some point, on some commonly-used libraries to handle low-level concerns.
The thing is, I'm not sure how i can depend on an external library for some piece of functionality (say for example dom manipulation), without tying it to my design.
Practical examples would help make a better point, but I'm not at the design stage yet, and I'm merely trying to avoid getting started on the wrong foot.
So I'm looking for some examples, guidelines, best-practices or maybe patterns that could help in this situation.
Any insight ?
EDIT : Bit of a clarification on why I'd want to do this.
My goal is to build something resembling more of an application framework than most traditional libraries like jQuery.
Think layered architecture, where the libraries would fit into the infrastructure layer (as per Evans' definition in Domain Driven Design), and handle things such as events, dom traversing and manipulation etc...

This is a very broad question, but if I were you, I would use jQuery as a base. It is a very easy library to extend and add functionality too.

I'd recommend grabbing a copy of ExtJS and taking a look at how they provide support for replacing the underlying core of their product. You can use their higher level libraries, such as grids, trees, etc, but choose to use YUI or prototype in place of their Ext core.
That should give you a good starting point.
Edit to answer comment:
Once you've downloaded ExtJS, take a look in the "adapter" folder. In there, you'll see the various adapters that exist to make ExtJS work with other libraries. You'll quickly see how they define functions that in turn make use of the appropriate underlying lib.

Segregate your code:
use the external libraries to the fullest possible, within their separate section of code.
Taking jQuery as an example, just designate a section for interfacing with jQuery and then use jQuery within that section of the library like there's no tomorrow, and give it interface functions that the rest of the code uses exclusively.
Frankly, if you integrate a library with your code and try to make it generic enough that you can trivially swap it out with something else, you're probably going to neuter the library to the point where you might as well have not included it at all.
Accept that you may need to rewrite if you end up swapping libraries, but prepare for that by giving the library-interfacing code it's own separate section, and you'll be able to write less generic, more powerful code with those external libraries and save yourself a lot of work.

This doesn't answer your pattern question, but a word about the frameworks. All of the modern JavaScript libraries are pretty good at playing well with each other, but some are better than others. Just make sure that they libraries don't monkey-patch the core objects with arbitrary properties or muck with the global namespace and you should be good to go. JQuery and YUI are both well designed and namespaced libraries. Dojo is also quite good, but a couple years ago when looking at all of the options, it seemed like Dojo encouraged the use of proprietary element attributes in markup as JS hooks. At that time Prototype was the library that mucked with objects like String/Array and didn't play well with others. I haven't looked/used Dojo or Prototype so take that with a grain of salt. I'm actively using YUI and JQuery in the same app; YUI for widgets and event management and JQuery for Selector/DOM manipulation.

I'd suggest you pick a single general purpose library or no library at all, depending on the requirements of the framework you plan to write. It's very difficult to make any kind of recommendation without more information, such as what your framework is aiming to achieve, who will be using it and in what kind of environment.
If you're considering writing a script of reasonable complexity then I would suggest learning the relevant "low level" DOM manipulation techniques for yourself. It's not as difficult as devotees of some of the famous general purpose libraries would have you believe.

Use some kind of interface to link to the library.
Don't do:
$("blah").something();
do
something("blah")
function something(id){
$(id).something();
}
Since you could call something() 20 times, it'll be simpler to update if the actual use of the library is in only 1 place.
It'll add development time and then complexity, but you won't be as dependent on a library.

I don't think this can be achieved very effortlessly. If you really want this behavior, I think you'd have to manually map the features that are covered by all libraries you want to include support for.
So that the implementation would look like:
yourLibrary.coreFramework = 'prototype';
yourLibrary.doStuff();
And your librar would treat it in the following manner:
function doStuff() {
var elem = getElement('id');
// do stuff with 'elem';
}
function getElement(id) {
switch(this.coreFramework) {
case 'prototype': return $(id);
case 'jquery': return $('#'+id);
/* etc */
}
}

Check out the jQuery or prototype frameworks.
If you decide you need to, then extend these.

Related

How to conciliate DRY and Loose Coupling in Javascript Libraries?

I am building my own JS library;
The idea is that the library should be comprised of small, independent modules, and some slightly larger utilities, that serve mainly to iron out browser differences.
I am having trouble getting anything done, because I am not being able to decide between staying dry or being loosely coupled.
An example? Given:
A small library that takes care of generating dom elements from a template
Another one that takes care of duck-typing issues (is_function, is_array...)
And a last one that creates modal boxes. That last one needs:
some type checking
will be creating the modals using only one function from the templating library
My options for the modal box library:
Be 100% dry, and dependant on the two other libraries. But that means if you are a user wanting to download only the modal box lib, you'll have to make with the two others
Allow users to pass an object of options on initiation that would allow them to specify the functions needed; defaulting to the ones of the libraries. This is better, but in practice, it still means, in 90% cases, using the provided libraries, as creating functions with the same signature might be cumbersome. Furthermore, it adds complexity to the modal box code.
Be 100% loose, and reproduce the functions needed in my modal box library; possibly more efficient because more targeted and there is no need to check for edge cases; but: any bug will have to be fixed in two places, and my download size increases.
So I am wasting time oscillating between the two extremes, refactoring a million times and never being satisfied.
I was going for a more generic question, but then I realized it is really pertaining to JS, because of the size & performance concern as well as the widespread usage.
Is there any known pattern to follow in such cases? What's the accepted way to go about this? Any thoughts are welcome.
[edit:]
This is the only article I found that spells out my concerns. Like the article says,
DRY is important, but so are [...] low coupling and high cohesion. [...] You have to take all [principles] into account and weigh their relative value in each situation
I guess I am not able to weigh their value in this situation.
Personally, I've always taken the view that Loose Coupling refers to creating seams in your code. In classical languages, such as Java, this is achieved by creating Interfaces which hide the concrete implementation. This is a powerful concept as it allows developers to 'unpick the seams' in your application and replace the concrete implementations with mocks and test doubles (or indeed, their own implementation). As JavaScript is a dynamic language developers rely on duck-typing instead of Interfaces: as nothing is frozen, every object becomes a seam in your code and can be replaced.
In direct answer to your question I think it pays dividends to always aim to decompose and modularize your code into smaller libraries. Not only do your avoid repeating code (not a good idea for a host of reasons) but you encourage re-use by other developers who only want to re-use parts of your library.
Instead of re-inventing the wheel, why not leverage some of the more popular JavaScript libraries that are out there; for example, underscore.js is a lightweight library which provides a rich toolkit for duck-type checks and Mustache.js may well take care of your templating needs.
Many existing projects already use this approach, for example, Backbone.js depends on underscore.js and jQuery Mobile depends on jQuery. Tools such as RequireJS make it easy to list and resolve your application's javascript dependencies and can even be used to combine all the separate.js files into a single, minified resource.
I like the concept of DRY, but your right it has a couple of problems.
Your end-user-developers will need to know that they need to download the dependencies of components.
Your end-user-developers will need to know that they need to configure the dependencies (i.e. the options to pass in).
To help solve 1. your project website could customise the download on the fly, so the core code is downloaded along with optional components. Like the modernizer download page.
To help solve 2. Rather than allowing users to pass in options, use sensible defaults to detect what parts of your packages have been loaded in the browser and automatically tie them up.
This loose coupling could also give you the great advantage that could also rely on 3rd party frameworks if the user already has them installed. For example selectivizr allows you to use jquery or dojo etc etc depending on what the browser has already loaded.
Perhaps you could use requirejs to help solve dependency management. I get the impression it's not really meant for libraries to use directly, but instead the end-user-developer... but it could be a nice fit.
I realise my answer doesn't answer your question directly, but perhaps it could help balance out some of the negative points of DRY.

YUI and/or jQuery for a new project?

If I am starting a new project how should I pick between using YUI 2, YUI 3 and jQuery?
I know there are a bunch of questions/answers already about can you use them together, but I am trying to figure out what criteria I should be thinking about to make my decision.
Are they overlapping?
Is one better at GUI and the other better at internals?
Do they play well together? My understanding from other questions is that they can live in different namespaces, so they can live together, but that doesn't necessarily mean that it is good to use both.
Thanks!
If you are familiar with neither, I personally have found jQuery's documentation and API easier to understand than YUI's, at least for simpler things. It also appears there is more jQuery related information than YUI on stackoverflow.
YUI does have its users and supporters though, so check it out in case you end up finding it suitable for you. It's got a huge library of additional modules you can use for complex web applications.
My usual advice would be to go with whatever you're familiar with, and I say this because I don't think it's worth dropping one to start learning the other from scratch. But if you are familiar with neither, then you should check out how easy the documentation for both is to understand.
PS I would not recommend YUI2 if you're starting anew as it has been superceded by YUI3, which is much better designed.
We need more information about the type and size of the project before a proper library can be suggested.
For example, if you're building a semi-complex/large-ish web app, I would suggest Dojo or ExtJs. Otherwise, for smaller projects, jQuery might be more appropriate. I cannot comment on YUI as I have not used it.
Impossible to say without knowing more details about the project. Use jQuery or Prototype for things like DOM manipulation and making autocomplete, etc. If you need a more powerful Javascript implementation take a look at ExtJS, which is basically a full stack framework for Javascript.
Both are JS frameworks and there to help you. YUI is known to be more natural in them and more closer to the original Javascript while jQuery is known as more easy and you find more jQuery users and support around then YUI. However, as said earlier, it depends on the project, if it is likely that you will be making your own custom widgets, I will suggest you to go with YUI but if it's like a simple e-commerce website in which you just need some fancy galleries and shopping cart, go with jQuery, you will learn and implement that quickly. I am not saying that you can not go more in depth with jQuery but my impression is that jQuery is more of a CakePHP for PHP like of framework which gets you off the grounds quickly.
In my opinion there is no need for you to use them side by side in a single project, that will just produce the over-head as both do whatever you want to do in them i.e creating dialog panels, autocomplete quick searches, event related utilities etc.
I am writing down a series of beginner and mid-level tutorials for YUI users, let me know if you find them useful or if there is anything else where I can help.
http://ciitronian.com/blog/tag/yui/

Writing a JavaScript abstraction abstraction - is this sane?

I've written a JavaScript application that runs off Prototype & Scriptaculous. I'm thinking of rolling it out in as an open source product & would like it to be able to run on jQuery as well — I typically use jQuery for most of my other apps, except the site this app was originally built for.
I was originally thinking about building two separate applications, but maintaining them would be time consuming. Instead I'm considering building a library abstraction layer that detects if the page is running jQuery or Prototype and then calls the appropriate methods. I'm not going to abstract the whole libraries, just the functionality applicable to my application — namely selectors, events & effect. The core of my app is under 500 lines of code, so there isn't too much I need to worry about.
So instead of calling $('id') I would call LA.$('id') (LA for Library Abstraction) which would call $('id') in prototype and $('#id') in query etc…
Does this sound sane? I can't think of any technical hurdles, although I would have expected someone to have attempted this before. I couldn't find anything similar in my searches.
I expect that if you support the libraries only partly then no one will choose to use it, as they would have to finish the support, and you may find that maintaining it will be a headache, as there will be requests to add more functionality.
If your application is so small, why not just switch to jQuery for it, and standardize on that, as MS has done.
You may run into problems with versions, as, if someone uses it, and they are using an older version of a library, and there was some API change, then they will be wanting you to add support for that library.
I believe Ext.Js does something similar. They have a concept of "adapters" which allow you to sit Ext.JS on top of any of the underlying libraries and it will just work. The key difference is that they are using a 1-to-1 model where you say which library you want to use and it joins the dots, whereas I believe you're trying to say "I don't know which one will be available but whatever one you find, go use it".
I don't think it's insane, but you might have some fun trying to work out which library to use, particularly if both are available.
Web development frameworks (Prototype, jQuery, etc.) themselves are designed to be abstractions on top of the various browsers that exist. You ask the framework to do one thing and it has the same result (ideally) regardless of the browser. So, here, you are proposing an abstraction on top of abstractions. Presumably because you want people to be able to use your tool regardless of what framework they have chosen for their site. While it sounds like an interesting idea, I would personally have to guess that it would not work out in the long run. Largely because you do not know what the future holds. Prototype used to be the number one use framework, now jQuery has surpassed it. Perhaps another one will be very popular in a year, what if you then want to support that framework? That can be a lot of conditional code that you have to add, and in addition, force being loaded into the browsers of those using your tool.
I say either pick a single framework to support and stick with it, or maintain separate libraries. Ideally, it would be really cool if you could write some sort of builder script. This would allow you to set framework rules in some list and the script would build separate scripts for each framework based on some core script and the rules list. I honestly am not sure how to best accomplish something like this but it would effectively give you that abstraction on abstraction power that you are looking for without it being visible to the end user.

MooTools and JQuery Side by Side

I just inherited some web pages which uses MooTools. I never used MooTools. Now I need to add some functions on the page, I wonder if it's a good idea to use jquery and mooTools on the same page?
Basically, I have 3 options,
Convert the pages to JQuery, which I have to learn MooTools to do that.
Write new functions in MooTools. I have to learn even more MooTools to achieve this.
Use both on the page.
Your opinion will be appreciated.
Opinion: Learn MooTools and then move on with it. Sounds like a great opportunity to learn something new. Why introduce an entirely new library with addition js bloat if you don't need to. If it'll solve the problem you're golden.
MooTools is a perfectly solid and acceptable Javascript library and I'd recommend you add it to your list of known technologies rather than tear it out and replace with JQuery. Mixing the two is not a good idea as you're likely to encounter obscure difficult to debug conflicts.
JQuery has had all the press of late, but it's by no means cut and dried that it beats every other library hands-down. Far from it. You might even find you prefer MooTools :-)
ADDED: For what it's worth my personal experience is that MooTools seems to play alongside other javascript code more nicely than jQuery. I've been handling several sites of late which have mixed in MooTools with various other pieces of Javascript for different effects/functionality and it's all seemed to play along together with minimal issues. OTOH pages that use jQuery tend to use jQuery versions of everything. YMMV of course.
Personally, I'd recommend not using both, as there are strange conflicts, even with jQuery.noConflict(). Go with one or the other.
If you do end up using both, be sure to use jQuery.noConflict() to ensure that using the $ doesn't conflict.
Using jQuery with Other Libraries
i'd say, depends on how the code is structured and what you need to do. mootools does render itself to easy refactoring and extending (this is, after all, partly the reason it exists) but it takes a while to figure best practices and so forth.
however, your learning curve from vanilla javascript or jquery won't be too steep, especially so if all you care about is DOM mantipulation, event handling and effects. things get more interesting when you decide to write / extend mootools classes and venture into prototyping - but you may not have to do that...
there are some pretty good tutorials around for most things as well as some demos on doing things through jquery and mootools (equivalent ones). http://jqueryvsmootools.com/ is a good example on how the same task can be done through either one, i'd recommend reading it before deciding.
whatever you decide, it is a bad practice to use two frameworks (when you can do without).
It depends on how big a project it would be to convert to jQuery, how much of your job is maintaing these pages (vs other pages that already use jQuery), what the urgency is for your first set of changes, etc...
It comes down to a cost comparison: how does the cost to your business to convert them to jQuery compare to the cost to the business for you to learn mooTools (and maybe keep both mootools and jquery in your head at the same time).
The only thing I can say for sure is don't do option 3. This isn't necessarily because it you can't make it work (and there will be challenges), but because you'll have to learn mootools to properly maintain the pages anyway. Once you do that, you may as well just keep them mootools rather than re-write everything or try to mix frameworks.
Personally I'm inclined to say convert it jQuery, since I believe jQuery is eventually going to corner the market. The implication then is that it will convert to jQuery at some point, and so the long term costs to business are probably best optimized by doing the conversion earlier while there's less to convert and mootools is still relevant so you can easily get help with the conversion. But that's certainly arguable.
jQuery and Mootools basics are close enough that moving from one to the other isn't much of a headache.
Whenever I'm given the choice between the two, I lean towards Mootools - especially if I'm intending to do any sort of effects or animations. Mootools's base FX libraries are far more robust and generate better results cross-browser in my experience.
Like others have suggested, you could take this opportunity as a learning experience. If you're satisfied with jQuery and don't feel the need to learn another framework, port the code over. You can't really go wrong with either in the end.
Since you're more comfortable with jQuery, I would just call jQuery.noConflict(); first thing, and write the functions in jQuery. That is, of course, if time is a factor.
There is a project that twists and prods Mootools to make it look like JQuery (a wolf in a sheep's clothing... or a golden coin painted to look like silver...)
I certainly think you should learn Mootools, but that might help.
I agree with those that are in favor of learning mootols, but i think that is even better if your take that decision because you finally think that learning mootools worth it.
So i think it would be nice to have some research over mootools capabilities.
I like this articule about this subject. And I think it can be useful for those reading this thread.
http://jqueryvsmootools.com/index.html

What JavaScript frameworks conflict with each other?

There are times when I want to use mootools for certain things and Prototype & script.aculo.us for others but within the same site. I've even considered adding others, but was concerned about conflicts. Anyone have experience, or am I just trying to make things too complicated for myself?
If you really, really want to do this, then you will be able to without too many problems - the main libraries are designed to behave well inside their own namespaces, with a couple of notable exceptions - from Using JQuery with Other Frameworks:
The jQuery library, and virtually all of its plugins are constrained within the jQuery namespace. As a general rule, "global" objects are stored inside the jQuery namespace as well, so you shouldn't get a clash between jQuery and any other library (like Prototype, MooTools, or YUI).
That said, there is one caveat: By default, jQuery uses "$" as a shortcut for "jQuery", which you can over-ride.
So, yes, you can do it, but you'd likely be creating maintenance headaches further down the line for yourself - subtle differences between framework functions may be obvious to you today, but come back in 6 months and it can be a whole other story! So I would recommend keeping it as simple as you can, and having as few different frameworks (preferrably 1!) as you can in your codebase.
AFAIK, all the popular frameworks are designed to be combined with other frameworks. I don't think combining them is that much of a problem. I would however discourage combining them purely from a case of bandwidth needs. A slow site experience is less forgivable than a more complicated development experience.
A recent question: jQuery & Prototype Conflict
Prototype.js library used to be very offensive and conflicted with many other libraries / code. However, to my knowledge, they recently given up with some really hard-core staff, such as replacing Element object etc.
You are better off sticking with a single framework per application. Otherwise your client will spend too much time/bandwidth downloading the javascripts.
That being said, Prototype and JQuery can work together. Information is on the JQuery web site.
My suggestion is to learn one (or more!) framework(s) very well so that you will be able to replicate the features you need without adding the overhead of multiple frameworks.
remember the more code that you push to the client the slower everything becomes.
From my experience I can say that some javascript libraries rather conflict with the browser, than with each other. What I mean is the following: sometime code written against some library will not well co-exist with the code written against browser DOM.
My Framework Scanner tool is useful for finding JS/CSS conflicts between libraries:
http://mankz.com/code/GlobalCheck.htm

Categories

Resources