Ok, i'm a newbie in this, i've been trying to study MVC patterns and Publish/Subscription patterns in Javascript/jQuery, however i believe that i haven't grasped the concept entirely.
Since i've been doing it alone, i humbly come here to ask for opinions about a small educational exercise that i tried to make following these patterns
http://jsfiddle.net/Couto/R62V8/
Ok, the exercise is mainly a login form, where the values are saved in localStorage, again it's purely educational, i now it's not safe in anyway and it should not be used in production.
Would you please tell me your opinion about the patterns used, did i fail at achieving the right use of patterns? Please hurt me if needed, i just want to learn, but i'm not sure if i'm doing it right.
jQuery's event delegation system is unto itself a form of pub/sub. In fact check this out, http://bugs.jquery.com/ticket/7547. You'll see under the hood it uses the event system and really only changes the naming scheme and works on a "global" context.
I have nothing against pub/sub, but feel you're adding a layer that doesn't need to exist in certain cases. Would triggering the correct function immediately after the event delegation fires rather than triggering a pub really be worse? If you remove the subscribe and the publish you'd wind up with nearly the same code without the added "complexity".
In other cases the publish/subscribe make a lot of sense. Your display/hash and set/login make a lot of sense as they aren't part of a traditional event that other code could subscribe/bind to.
One could make the argument that by using pub/sub everywhere, including in event delegation, you're abstracting away your reliance on outside code from having to write event delegations of their own, which removes their worry about what element to bind the delegate to. If you're writing big complex applications, go ahead and abstract it out to that level. If you're not planning on writing big applications weigh the benefits cause YAGNI might apply here.
Related
I am on a new project and our job is to rewrite an e-commerce website that is having performance problems on mobile devices.
We are re-writing the javascript based on a more object-oriented/modular architecture which I think is great! However my team lead said that we should remove all the jQuery calls and replace with javascript like so domElem.querySelectorAll(query) , which has better performance. I understand jQuery does some kind of caching in the background which can create memory issues.
I am a little sceptical of this, firstly because it seems like a case of 'premature optimization', that is, we should find the bottle-necks first before we re-write anything. And secondly I haven't found anything on the internet that says that jQuery has significant performance problems.
The current website does have a lot of overlapping dom branch queries which I think creates a lot of redundancy. That is there is too much querying happening, and on our new architectual approach we are restricting our object/module to fewer dom queries and more targeted dom queries which is great. This does need to be re-written.
But whether or not we use domElem.querySelector(query) or $(domElem).find(query), I can't see there as being much of a difference. Is my thinking right?
Some tests are done here (check other revisions as well). Good detailed discussion is done here over pros and cons of using jquery over javascript.
Also want to point out that jquery doesn't do any caching of selectors.
The thing we often forget because of using Javascript frameworks all the time is that jQuery is not a framework.
Obviously, if you do the exact same one-operator action using the jQuery '$' object and using a direct DOM method like getElementById, the latter will be noticeably faster as jQuery itself is written in Javascript and does a lot of background stuff.
However, nothing (except code readability) prevents you, as a developer, from combining jQuery with plain Javascript: using plain Javascript wherever possible and only using jQuery functions that provide complex functionality and take some time to write and optimize from scratch. There are a lot of those in jQuery: providing browser-independent css, serializing object and doing lots of other cool stuff.
It depends on the application but usually performance troubles are related to badly-designed algorithms, not the use of jQuery.
In any case, if your application does a lot of DOM-manipulation, it may be worthwhile to re-write it using plain Javascript and test. Keep the library, just don't use it for simple operations you can easily write without it.
If your application is heavily-reliant on jQuery functions with complex functionality, removing it is out of the question.
I myself use this combined approach: everything simple written in Javascript with jQuery functions for stuff that is difficult to implement.
Also, a good place to dig around if the app has troubles with performance is the DOM-manipulation. Those operations are very heavy compared to almost everything else in Javascript. You may be able to cut down on time by rolling several operations into one, building finished objects with one constructor, instead of creating empty ones and assigning properties one-by-one, etc.
Sorry, if the answer is a bit vague but it's difficult to be precise in this case without seeing the code and running tests.
Let me quote Uncle Bob about this discussion "Architecture is about intent, we have made it about frameworks and details"
Premature optimizations needs to be considered carefully.
They often result architectural decisions that are not easily revertible.
They introduce code optimizations that are usually specific to the problems they solve, which makes the code less abstract thus hard to
maintain, and more complicated thus prone to more bugs.
They tend to be prejudice and not objective, sometimes without any real comparison to other alternatives.
The problems they are trying to solve tends to be overestimated, to the degree of non-existent.
I'm not a big expert on Web development but if possible, you should always push this kind of decisions to the end by separation of concerns, and good abstraction.
For example over the parts that generate the java-script code you can have an abstraction of JavaScriptWriter, and use different frameworks. This way you can use JQuery at the beginning, test the system and only then replace parts you know to be inefficient.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What is the best practice for Dojo dijit creation?
A purely declarative approach (D)
A purely programmatic approach (P)
A combination of the two (D&P)
Criteria
Easiest to maintain
Fastest to develop with
Most intuitive
Best performance
Most functionality and flexibility
Context
I've been working with Dojo for a little less than a month now, and I've recently started working with the dijit library. One of the well-advertised aspects of dijits is that they can be declared programmatically or declaratively. I always like to approach a new set of tools with an understanding of best practices and some general idea of which approach has which strength/benefits for a particular application.
The information below comes from some personal experience with both styles, as well as the reference material I've been able to find, which isn't a whole lot. This link is the only one I've found in the official Dojo documentation on the subject, and this post provides some outside perspective with a basic presentation of how the code for each looks for simple scenarios. Both links are for older versions of dojo, before AMD was introduced in version 1.7.
Programmatic
Separates Dojo from HTML, which preserves semantic purity of HTML
Puts event handlers and widgets in the same place, increasing readability
Seems to make it easier to assign values to attributes dynamically (e.g. create unique IDs using a function)
Declarative
Rapid development -- intuitive, implied nesting, widgets defined like normal HTML elements
Valid HTML5 through use of data-jojo-* attributes
Does not preserve semantic purity of HTML
Event handlers come from outside scripts, creating some complexity and reducing readability
Initial parseOnLoad can slow up-front widget setup
A note on responses: Please address each of the criteria in your response. Feel free to propose any additional criteria you think are important. I am by no means an expert at evaluating best practices.
Update:
After browsing around for more info on this, I found another post with similar thinking, which provides some useful context on what implications these style differences have.
I don't think there isn't a best practice. Personally I like to use a combination of both programmatic and declarative code.
I think it makes more sense to seperate the presentation layer from the business logic layer (somewhat like the n-tier architecture). I mean, what's the difference between a dijit/form/TextBox and the standard <input type="text" /> HTML element? They're both part of the presentation layer and they both have the same purpose. The only difference is that the one is a custom element while the other one isn't.
But on the other hand, I consider event handling and validation as business logic, so I would put these into a JavaScript. You could also declare your dojo/store objects declarative, this is also something I don't like because it doesn't have to do with my presentation layer.
Now, back to addressing your points:
Easiest to maintain: If I had to change a dijit widget, then I would probably look into the HTML (seperation of concerns; presentation <--> business logic). It's also easier to find. For example, if you know that the dijit widget is right below the title and just above a button, then you exactly know where to look for in your HTML code. If we made it programmatically, it could be anywhere in your code.
Fastest to develop with: Well, maintaining and developing is a bit the same, but another advantage of declarative markup is that the markup you write actually serves as a placeholder while programmatically you will have to assign each property to a value.
Most intuitive: I also address this in the first part (easiest to maintain). I also think that it's pretty good that they also use a few standard HTML attributes like title, value, placeholder, ... . I don't think this pollutes your HTML markup, but increases readability too.
Best performance: It's not the fastest way, I'm well aware of it. But the margin is pretty small, it's not that it is a huge difference. You could also tweak it by disabling parseOnLoad and manually parse the nodes you need to be parsed. Another nice thing is that the end user "sees" something. For example, if you write the following code:
<select data-dojo-type="dijit/form/ComboBox"></select>
<input type="text" placeholder="Text..." />
The end user actually sees something when he loads the page (and it's pretty representative of the real result), even is the page is not parsed. When you create everything programmatically, the only thing the user will see is a white page.
Most functionality and flexibility: Because I think combining declarative and programatically way of developing, I can enjoy the benefits of both. You're somewhat blocked in doing everything in a declarative way (event handling really looks messy if you put it all in your HTML), but I would write those in JavaScript code.
On the other hand, it really looks messy when you're creating a widget programatically (that's an opinion), so I can define these in HTML where it's a lot easier.
So in the end I like to write a combination of both. Event handlers indeed come from outside scripts, but if you write proper MVC applications, they always will (since it is a part of the controller while the markup itself is part of the view).
I'm not saying you have to put all event handlers in one file, no, thanks to the AMD loader you can easily add other scripts. If you group all interaction of a certain widget (or a group of widgets) into files and name these correctly, it's pretty easy to find things.
The more files, the smaller the files usually are and the easier they can be read (so complexity goes down and readability goes up). You might end up with a lot of files, but if you name these correctly (and document them maybe), there should be no problem.
But in the end, this is an opinion, there are probably other opinions too which are as good or even better than mine. Sometimes it's also depending on the situation, if performance really is one of the biggest requirements, then defining everything in JavaScript might be the best solution too. It's not like these rules are carved into a stone somewhere.
Well, I am basically exploring knockout and and understanding different features that it has to offer. I really liked the templates and two way binding with some observation with it. Now, it is implemented in our company recently for may modules but there is a really big talk about how event driven it is and how beautiful it is.
Well, when they argue that it is very event driven, they pit it against JQuery. Their argument is that in JQuery anyone can come in and bind a button's onClick anywhere and it gets messy sometimes when there is no set standard for keeping all the events for all the controls in the same place and it makes code hard to manage.
My argument is that may be Jquery needs explicit management of code to achieve this but event driven programming is not something exclusive? asp.net web pages have it with it's code behind for years and how about classic ASP with ancient JavaScript with all it's OnClick events?
Am I missing anything here?
Well events are not new.. Since the inception of a button control, it should have been there in one way or another. But the difference is how event are being used and how maintainable your can be.
On jQuery and Knockout, I dont think it is a question of events, but a question of the design pattern. jQuery, uses events (yes with more code in certain instances) but it doesn't specify a particular pattern to be used. On the other hand KnockoutJS brings in MVVM pattern with bi-directional data binding, that will give you a structure required for writing complex applications.
In my opinion, use of a pattern will certainly enhance your code maintainability. You may even implement MVVM, MVC or MVP with plain jQuery too. But that will require bit more effort as jQuery is not made to specifically work as such. For example if you use BackboneJS that will let you to organize your code on MVC pattern and there you may use jQuery for event bindings.
Each of the library has it's own place depending on the use case. For simple one way event handling, you might not need knockout viewmodels but just do that clean with jQuery. But for complex UI with high bidirectional messaging, knockout will do things with lesser amount of code.
Take other scenarios as well... Knockout needs you to tamper the HTML with it's custom attributes. What if changing HTML is not an option for you? jQuery has a better use case there. Use jQuery, Knockout, Backbone or BoilerplateJS we per the use case.. not just because someone think it's cool :)
So I have a fancy GUI in jQuery, which has gotten relatively complex. I would like to write tests for it, e.g. using assert(). However, it seems that writing such tests is difficult because GUIs don't manipulate data or make computations: they are just superficial interfaces to please the user.
So how does one generally write tests for GUIs?
assuming your code is fairly clean (modular and loosely coupled pieces of functionality that work together rather then a few uber functions), the first thing to do is choose a test framework. I recommend jasmine, because it fits the way I like to write tests, but if you are looking for more of an xUnit clone, qunit is also very well made.
If your code is not pulled apart (like 99.99% of javascript in the wild), I would first look at how to make jquery plugins, and extract as much as you can into them. Testing uber-functions that do loads of things is a scary proposition, but when you are talking about a module that does a single thing, testing gets much easier.
Finally, there is a bit of a learning curve with both how to structure complex javascript, and how to test it. Don't give up! Contrary to what some people would have you believe, javascript is very testable nowadays with very solid libraries and there are many people doing it (I just spent all day working on complex functionality, was practicing TDD the entire time, and it never felt clunky or unnatural)
Good luck, and feel free to ask for clarification if something here is unclear :)
EDIT:
By "pull apart" I mean move to a more modular approach rather then gigantic functions. In jQuery, the first step is with plugins, which will take you pretty far. If you are making a javascript "application", where most of your logic is in the front end and the back end is mostly for persistance, I would look at stuff like Backbone.js, which will help manage a very high level of complexity, but is totally overkill if you don't need it.
Going back to extracting plugins, try to find pieces of functionality that are sort of contained. I wrote a quick plugin today to remember the state of checkboxes in a table with paging, where the contents of the table get swapped out programmatically, but if a user checks a box on page one (but doesn't save), goes to page two, then back to page one they should still see that box checked.
If that checkbox code was inline in the paging code, it would make the paging code WAY more complicated. By pulling it into a plugin, it only complicates the paging code a little bit (calling $(table).saveCheckState() when a page unloads, and $(table).loadCheckState() when a new page loads) It also makes the testing very straightforward, all I need is a div with a few checkboxes to test the checkbox code, rather then needing to add more to the paging tests which are already pretty complex.
Not knowing your background or level of experience I would hesitantly recommend reading clean code if you want to learn more about this sort of stuff. Unfortunately is it java oriented rather then javascript, but most of it is universally applicable in any object oriented language (which javascript can be), and is probably the best intro level book into this topic. If you do full stack development (rather then just front end), have at least a working knowledge of java, are a junior/intermediate dev who wants to improve their craft, its one of those books everyone should read. If those things aren't true, it may end up just being confusing, or just not really be much use to you. So take the recommendation with a grain of salt :)
Your answer is in GUI itself - User interface.
GUI's are best tested with people. You should check out http://ux.stackexchange.com which is dedicated entirely to the user experience.
I think this is important, because I'm sure your GUI is to the point where it is solid, as you've done the unit testing on non-graphical elements. Through your own testing you've made it this way - now, you should see how other people interact with it, how they break it, and what they like or don't like about it. Then you make changes and do it all over again.
(Ok, I know this isn't unit testing. But seriously, the options out there for heavy testing of jQuery stuff are not that fun to deal with!)
Is it good or okay to have several frameworks in a project, or is it bad because it gets cluttered (= a mess), and the loading times maybe get's longer. Does some 100 K matter really? Or should you stick with one?
It's generally better to pick one thing and stick with it, for a number of reasons:
Fewer dependencies.
Lower complexity.
Easier to maintain.
Faster loading times.
No likelihood of dependency conflicts (i.e. jQuery can't conflict with your other Javascript framework if you only have one).
Lower debugging times.
It's true that an extra ~50k these days probably isn't going to kill anybody for a personal site or blog. The benefit comes when you scale to larger sizes, and all those extra 50k hits are eating into your bottom line. But even if you're just doing this for a small site, the savings on your sanity from figuring out problems quicker will easily be worth it.
That said, if you just need one part of a specific piece of a Javascript framework, the larger ones are often split into logical chunks, so that you can just take the piece you need rather than the entire framework. Most are rich enough these days that if framework X has a feature you want, but you're using framework Y, you can pretty much just map the source code for that feature directly into framework Y.
If you can load the javascript library from a repository where it would be cached on the first visit, then i don't really see any problem with that.
But, for uniformity sake i will go with one javascript library.
But, if you really have any strong reason to use two, then go ahead. As far as it is cached the first time.
Just adding something to John's words, one could choose, for example, JQuery, which allows you to use it without clashing with other libraries. I remember that once, I had troubles while trying prototype and mootools because I wanted some things from the former and some other from the latter, but it was long ago and maybe it was solved.
Somehow, I've found that it's easier to maintain a single library and there're a few real differences between them. It related more to the way each one approaches to map documents and apply things to their elements, which causes differences in response time, but the goal happens to be the same.
Good luck with your choice :)
PS. If you gzip and fix etags in the stuff you offer in your webapps, the difference between loading one or two js frameworks is not reeeeaaally important -unless you're in facebook, meebo or so!-. I've found that the yahoo! recommendations are helpful.
http://developer.yahoo.com/performance/rules.html
I wouldn't run two frameworks unless there was really no alternative. They often aren't written to play well with others; there are lots of potential ways they can cause unwanted interactions.
For example with jQuery, a lot depends on the user-data key identifiers the library adds as attributes to element nodes. If you start messing with the structure of the document by cloning, adding/removing and so on from another framework (or even just plain DOM methods) then those identifiers aren't as unique as jQuery expects; it can easily get confused and end up failing to call event handlers, or tripping on errors. This sort of thing isn't fun to debug.