Unobtrusive Knockout - javascript

I've recently got up to speed with Knockout and I think it's a fantastic framework. However I have one concern.
I'm finding that in non-trivial binding cases, I have snippets of javascript code creeping into my view (markup). In fact quite a few code samples in the Knockout documentation demonstrate this too.
Does this make Knockout inherently obtrusive?
Should I just accept it for what it is and not be worried in practice?
Or are there any patterns/techniques I should be employing to make Knockout unobtrusive?

Great question. I've been writing complex KnockoutJS views for awhile and was never satisfied until I switched to Ryan Niemeyer's class binding provider.
The Knockout ClassBindingProvider allows you to declare your bindings in a JavaScript object and then reference them from a data-class attribute similar to how css classes work. It works great!
See an example TodoMVC app.

Try to keep Javascript out of the bindings and only use it for metadata
so instead of doing
<span data-bind="visible: errors().length > 0">You have errors</span>
Use a computed observable
<span data-bind="visible: hasErrors">You have errors</span>
Update: I went ahead and created a Convention over configuration API for KO
It can be found here https://github.com/AndersMalmgren/Knockout.BindingConventions/wiki
Instead of doing <button data-bind="click: save">Save</button> you're doing <button data-name="save">Save</button>. The library will understand by convention that you want to hookup the save function to the button click handler. By convention it will also bind enable if a canSave member is present.
http://jsfiddle.net/3Ajnj/15/

Should I just accept it for what it is and not be worried in practice?
My understanding is that "unobtrusive" means a few different things.
One aspect of "unobtrusive" is that websites should maintain core functionality on browsers with limited JavaScript support or none at all. To that end, your concern for this principle should depend on your target audience. I've worked on projects where I knew my target audience well enough that I had the luxury of saying, "if you want to take advantage of this web app, use a modern browser like Chrome, with JavaScript enabled." In this case, feel free to go buck wild with the latest, awesomest front-end frameworks out there.
I've worked on other projects where this was not the case we had to be very careful with our usage of frameworks like Knockout. If you're relying heavily on Knockout to do core functionality in your application, then your application is inherently obtrusive. Whether or not this should bother you depends on your target audience.
Another principle of "unobtrusive JS" is a separation of concerns between JavaScript and HTML. I actually debate how strictly important this principle is. I think a more important principle is a separation of concerns between view model logic and display logic, following the MVVM pattern. Knockout does a fantastic job of encouraging clean separation of view/vm concerns, even if you put a bit of JavaScript logic in your data bindings. As long as it's strictly view logic, I think it actually belongs in the view.

I recommend you, that you pay a visit to Ryan's blog and read: "Simplifying and Cleaning Up Views in KnockoutJS", if you haven't done so...
http://www.knockmeout.net/2011/08/simplifying-and-cleaning-up-views-in.html
It explains some nice ways for you to refactor your code, so it doesn't clutter the html and keep it more clean.

An alternative, to the binding provider suggested in the selected answer, is the knockout.unobtrusiveBindingProvider, which is "an unobtrusive, convention-based binding provider for Knockout JS that enables a clean separation of HTML and Knockout databindings".

Related

Is it possible to combine Dojo with other JS frameworks?

We are using Dojo (1.9.3) as a JS framework for building a single page application. We are however spending too much time on the quirks of Dojo, so even simple tasks take a long time to implement. And since there is lack of proper documentation, we often have to resort to reading the source code and then implementing a workaround.
I feel that we would speed up development, and make it easier to maintain the code if we moved to some other framework. Our codebase is rather large, since it is a complex application, so we do not have time to re-write the whole thing at once. I was therefore hoping that it might be possible to combine Dojo with some other framework, so that we can move away from Dojo incrementally. I have only dabbled with these other framework in my spare time, and only wrote some small example apps, so I do not feel that I can really say whether or not they would play well with another framework, so I'm hoping that some of you out there can.
The frameworks I've been looking into - in the order of what I'd prefer based on my short investigation, but feel free to convince me otherwise.
Ember
React
Polymer
Angular (last due to me being scared of the major 2.0 overhaul)
While the main question is whether or not it is possible, please also advice on if you think it is a bad idea to do so.
The most I can say from the Dojo end of things is that Dojo itself is a toolkit, not a framework per se, and thus generally should not interfere with other scripts or frameworks. The reverse, on the other hand, can't always be said. So while I can't speak for all of the choices in your list, I do not think that Dojo itself will get in your way.
One possible exception I can think of is if any of the frameworks in question augment native prototypes, particularly Object, since that will affect enumerable properties in all objects and can wreak havoc on any scripts that use for...in loops without hasOwnProperty.
The only other exception I can think of is whether any of the frameworks in question for some reason do not coexist well with an AMD module loader.
That being said, I would also advise you to take the "promise" of frameworks with a grain of salt - you say that right now you are finding that implementing things with Dojo takes effort, and naturally the frameworks you list are attractive because they make certain parts of application development easy by offering patterns and conventions - but the question you should ask is, how hard does your framework make your job the moment you need to do something outside or against those conventions? Dojo may have a learning curve, but it generally doesn't prevent you from doing anything.
You can use them together, but it also depends on what you're trying to do. Some actions might take more time for integration than others.
Dijit
I only have experience with Ember.js and AngularJS, but a common concept in these frameworks is data binding. Data binding allows you to simply update the model and the view will reflect the changes in the model.
However, these usually do not work nicely with widgets. Widgets (like the Dijit library) create their own DOM and because of it, frameworks like Ember.js or AngularJS are not "aware" of these changes and cannot update the view in that case.
To make it work, you will have to wrap your widgets into components (Ember.js) or directives (AngularJS). An example of such wrapping can be found in this answer.
Dependency loading
Dependency loading might be confusing. AngularJS comes with their own dependency injection system, and means that you will have to use the Dojo AMD loader for Dojo modules and AngularJS dependency injection for AngularJS. The two work nicely together as far as I know (I've seen examples with the RequireJS AMD loader, so it should be possible).
With Ember.js I had a bit more troubles integrating with the AMD loader. The creator of Ember.js (Tom Dale) does not believe in AMD, and I've seen several issues trying to load Ember.js components with an AMD loader.
It all depends on how you wish to use these frameworks and what extra effort you want to make. To me it looks like you're not even sure what to use these frameworks for, since React.js or Polymer has a completely different purpose than AngularJS or Ember.js for example.

Angular and Semantic Markup/Separation of Concerns

Perhaps this isn't a good place to ask this, but I'll try to make it as objective and answerable as possible.
I've been playing with Angular.js and really liking it, but I have a question about its philosophy. Here's a snippet of code from the Angular site for a controller.
<div ng-controller="TodoCtrl">
<span>{{remaining()}} of {{todos.length}} remaining</span>
[ archive ]
<ul class="unstyled">
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</li>
</ul>
<form ng-submit="addTodo()">
<input type="text" ng-model="todoText" size="30"
placeholder="add new todo here">
<input class="btn-primary" type="submit" value="add">
</form>
</div>
This is basically HTML with Angular directives sprinkled in. The one that I find potentially susupect is this: archive.
When Jeffrey Zeldman wrote Designing With Web Standards, it became a best practice to separate markup (HTML), presentation (CSS), and interaction (JS) into different files for maintainability.
My question is, how does Angular not violate that? I'm actually really enjoying it, and finding it quite powerful, but what is the difference between binding a click event to an a element like that in the markup, and writing this vestige of pre-web-standards code:
<a href='#' onClick='showAlert()'>Click here</a>
<script>
var showAlert = function(){
alert('hey');
}
</script>
Helpful answers might refer to documentation in addition to personal experience with using the framework.
I'll start with the piece of code that you find suspect and the fundamental difference between how it is handled in AngularJS vs. plain HTML and Javascript.
This is basically HTML with Angular directives sprinkled in. The one
that I find potentially susupect is this: <a href=""
ng-click="archive()">archive</a>.
This looks awfully similar to something we would have written 10 years ago:
archive
However, there is a fundamental difference between the above HTML and the AngularJS implementation. For AngularJS, the archive function is located on a scope that we control and can manipulate through the use of controllers. The raw JS example requires that archive be in the global namespace (which is bad for many reasons).
But, we can still see what the onclick event binding was meant to do; it was meant enable one to declaratively build behavior into a view, and let JS handle the implementation details. AngularJS does this, AND provides a way to organize the difference scopes/contexts of our view in a way that is not possible with regular HTML.
Yes, AngularJS involves extending HTML by moving more of the presentation and binding concerns into the view. The good news is we are heading that way with HTML6. Here are some select quotes from http://html6spec.com/:
Imagine being able to mark something up the way you want to mark it
up. Imagine changing <div id="wrapper"> to <wrapper>...
The web is moving towards a giant app store and we need to embrace it.
The markup we use shouldn't work against us, it should work for us.
This spec is to do just that. To finally break free of fatuous rules
and standards and to give us, developers, total freedom to code as we
please bringing the web a more semantic, clean, and human readable
markup.
In a way, AngularJS brings us all the goodness of HTML6, but allows us to use it today. How the web is used has changed drastically in the past 15 years and our tools are still lagging very far behind. Lucky for us, the future is a beacon of light and hope, and AngularJS brings the future back to the present.
Quite an interresting observation and question, and a good answer by #mortalapeman.
I'd like to add that the function of the html, and our expectations of what it's supposed to do is changing. We've been taught to keep our behaviour completely out of the document (html) and rather set up our code to hook into the document without polluting the document.
With Angular the job of the html isn't simply to be a document, it is to be the presentation layer of an application, which to me is a much bigger job. And to fill this job Angular (and similar frameworks) allows us to do two-way binding with our data and behaviour in a declarative way while, as mortalapeman points out, keeping our data and behaviour nicely scoped and separate, as well as testable.
In fact, now that I think about it, it's actually a bit silly to maintain a position that your html should be a pure document, but at the same time contain buttons and other controls, indicating that it is more than a document. Maybe it's just me, but I find that paradoxical. It makes perfect sense to me that we declare what action should be triggered when operating a control.
I was studying Angular recently and had the exact same thoughts, doesn't this violate separation of concerns? The examples they give at their site "Do violate separation of concerns!" After being involved with MVVM and MVC over the past 10 years, I'm thinking that Angular is a step back to the Cold Fusion days. Not that Cold Fusion and Angular are not strong, they just are enablers for bad design.
All SDLC studies show that 50-60% of total cost of software is in maintenance, not development! But most developers think (because of due dates) they just have to get it out there, and to their credit, they do! However, projects end, developers leave and the rest are left wondering how to support this code base.
We've know about OOP and OOD for years and just recently saw attempts to bring Javascript into this concern with extensions like JQuery Although until Javascript truly becomes an OOD language it and all extensions of it, will not truly get there. The comment above "gloabal variables are bad" is a good comment, but in strongly typed languages, it's NEVER a concern. The only time these types of issues happen is when the framework supports it out of the box! Strongly typed languages can have global vars if needed but scoping is king in those languages and it is one of the first things taught.
My experience over the years is that programmers are first 1) Quick to get the job done before they recognize the patterns that make up good technique. 2) There are tons of code in every major institution that needs severe re-factoring 3) Problems in extensible are not seen until many years later 4) The effort to re-tool is huge! All of this is good news for job security, yet at the same time, why not just do it correctly from the start?
JQuery, Javascript and even Angular have their place, but they are also frameworks that encourage bad design for those unaware. I've found the single most important pattern in all of programming is the "Observer Pattern" which we see in the ability to create Event Handlers and to create Events. Decoupling then becomes very high on the list as well. If you have code that is big on events and event handling chances are, you are headed in the right direction. If you are reusing code and being strict about not repeating things you are doing well. Finally if you are into re-factoring with a passion and really understand the power of interface based programming techniques you are doing well. Oh yes one other thing, if you know what dependency injection is all about, you are a 5 star general in the Army of Programmers. March on, good soldiers!
I have been using Knockout.js (which is pretty similar to angular regarding the data-binding concepts) for the past two years on a large project. The main advantage I see in having only some function names in the markup, instead of the entire function implementation is that the implementation can be easily changed without altering the markup. Especially if the markup is not fully controlled by you, as was in our case.
The designer altered the markup to suit the visual requirements, while we just told him not to mess with data-bind attributes. Of course, sometimes he changed the markup so heavily that we needed to alter the data-bind attributes, but this mostly meant moving them from one tag to another, the implementation was unchanged.

Best practice to create Custom UI framework in JavaScript [closed]

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
I want to create a custom UI framework in JavaScript for web applications (like Google Docs ui) (do not confuse with web application that deploy using languages like PHP, Python, etc.). However, after reading several books about web development, I understand that the best website is layered as follows:
Structure in HTML
Presentation in CSS
Behaviour in JavaScript
So there are several approaches to creating my own HTML document and control it in JavaScript. However in this approach HTML and CSS will be mixed, like in case of extJS UI. I am confused now, and I need some answers from experienced developers on how to write this kind of framework.
If HTML, CSS, and JavaScript is mixed.
What was advantages?
What was disadvantages?
Is there are other methods?
What was the usual type of creating UI frameworks?
I apologize that this answer is extremely long and at times may seem somewhat off-topic, but please keep in mind that the question was not very specific. If it is improved, or made less general, then I will gladly remove the superfluous parts, but until then, just bear with me. This is somewhat of a compilation of the other answers here, in addition to my own thoughts and research. Hopefully my ramblings will be at least somewhat helpful for answering this question.
General Tips for Frameworks
Frameworks are a ton of work, so don't spend all of that time for nothing. Work Smarter, Not Harder. In general, you should remember these things when creating a framework:
Don't Reinvent the wheel: There are tons of great frameworks out there, and if you create a framework that does the exact same thing as another framework, you've wasted a ton of your time. Of course, understanding what goes on inside another library is a great way to make your own library better. Quoting #ShadowScripter, "knowledge -> innovation." However, don't try to rewrite jQuery by yourself. :)
Solve a Problem: All good frameworks (and programs) start with a problem they are trying to solve, then design an elegant solution to solve this problem. So don't just start writing code to "create a custom UI framework," but rather come up with a specific problem you want to solve, or something you want to make easier. jQuery makes selecting and manipulating the DOM easier. Modernizr helps developers identify the features supported by a browser. Knowing the purpose of your framework will make it more worthwhile, and may even give it a chance of becoming popular.
Fork, don't rewrite: If the problem you aim to solve is already partially solved by another framework, then fork that framework and modify it to fully fit your needs. There's no shame in building of the work of others.
Optimize and Test: This is kind of a no-brainer, but before publishing version 1.0 on your website, test every single part of the function, under every single possible scenario, to make sure it won't crash and burn in production. Also, another no-brainer, minify your code (after testing) for performance benefits.
DRY and KISS: Don't repeat yourself, and keep it simple, stupid. Pretty self-explanatory.
Stick to Stable: (This is mostly my personal opinion) Unless you're trying to create a framework specifically targetted to HTML5 in Chrome 31, using experimental features and unstable code will make your framework slower, uncompatible with older browsers, and harder to develop with.
Open Source: (Another of my opinions) It takes years for huge companies like Google with thousands of dollars invested to create frameworks (e.g. AngularJS) so it is an excellent idea to make your source openly available. Having a community of developers contributing to your project will make development faster, and will make the end product faster, bug-free, and better all around. Of course, if you're going to sell it, that's another story...
For more information about best practices when making libraries, take a look at these links:
Javascript Library Design
Javascript Module Pattern: In Depth
Best Practices in Javascript Library Design
Building a Javascript Library
Types of Frameworks
The first thing you need to think about, as mentioned above, is what functionality you want your framework to provide. Here are is the list of types of frameworks/libraries (thanks to #prong for the link). For a much more comprehensive list, see jster, which has 1478 libraries, put into 8 categories, each with several subcategories.
DOM (manipulation) related
GUI-related (Widget libraries)
Graphical/Visualization (Canvas or SVG related)
Web-application related (MVC, MVVM, or otherwise)
Pure Javascript/AJAX
Template Systems
Unit Testing
Other
As you can see from the link, there are already dozens of libraries and frameworks in each of these categories, so there's not exactly much room for something new. That being said, I don't want to discourage you- who knows, you could create the next bootstrap or jQuery. So, here are some resources about each type of framework.
Note: you can't say that any type is better than the others, they simply are designed for different goals. It's like comparing apples and oranges.
DOM (manipulation) related
These types of libraries are designed to interact with, modify, and control the DOM of a website. Here are just a few of the things they do:
Select Elements in the DOM ($("div#id .class"))
Add/Remove Elements in the DOM ($("div#id .class").remove())
Edit Attributes of Elements in the DOM ($(div#id .class).height("30px"))
Edit CSS of Elements in the DOM ($(div#id .class).css("property","value"))
Add listeners for various events taking place in the DOM ($(div#id .class).click(callback))
The most notable of these, of course, is jQuery, and it has one of the largest user bases of any Javascript library. However, it is by no means perfect, and if your library wants to compete, the best thing to do would be to make it excel in the areas that jQuery fails- speed, fragmentation, and "spaghetti" code. (The last two aren't completely in your control, but there are certainly things that you can do to make it easier for users to use the most update version, and keep their code maintainable)
GUI-related (Widget libraries)
I think that this may be the type of framework you're looking to create. These types of libraries provide widgets (datepickers, accordians, sliders, tabs, etc.), interactions (drag, drop, sort, etc.) and effects (show, hide, animations, etc.). For these, people are looking for quantity- the best frameworks out there have several useful widgets/effects that work well. This is one case where it's "the more, the merrier," of course, if it works properly.
Graphical/Visualization (Canvas or SVG related)
The purpose of these libraries is to control animations on the page, specifically on an HTML5 Canvas. These feature animations and sprites for games, interactive charts, and other animations. Again, successful graphical libraries have many, many sprites/animations. For example kineticjs has over 20 different sprites available. However, make sure that quantity does not compromise performance and overall quality.
Web-application related (MVC, MVVM, or otherwise)
Basically, the idea is to provide a layout for the users to put their code in, typically separating the model (data) from the view(what the user sees), with a small controller to provide an interface between these two. This is known as MVC. While it is by no means the only software pattern to base a framework off of, it has become quite popular recently, as it makes development much easier (that's why Rails is so popular).
Pure Javascript- AJAX
This should really be two categories. The first, AJAX libraries, are often paired with a server side library and/or database (though not always) and are designed to make connections with a server and get data asynchronously. The second, "Pure Javascript" are designed to make Javascript easier to program in, as a language, provide helpful functions and programming constructs.
Template Systems
This might also be the type of framework you're looking to create. The idea is to provide components that developers can use. There's a thin line between Template Frameworks and Widget Frameworks (which twitter bootstrap, one of the most popular template frameworks, crosses a lot). While widget frameworks just give a bunch of little elements that can be put in a site, template frameworks give structure to a website (e.g. responsive columns), in addition to making it look good.
Unit Testing
This type of framework is designed to let developers test, or systematically ensure the correctness, of their code. Pretty boring, but also really useful.
Other
This type of framework is for really specific purposes that don't really fit into any of these other categories. For example, MathQuill is designed for rendering math interactively in web pages. It doesn't really fit into any other category. However, these types of frameworks aren't bad or useless, they're just unique. A perfect example is Modernizr, a library for detecting a browser's support for features. While it doesn't really have any direct competitors, can't be put into any of the other categories, and does a very small task, it works very well, and is very popular as a result.
More Types
There are a bunch of other types of libraries. Below are the categories (I'm not listing subcategories because that would take half an hour to copy down) that JSter puts their 1478 libraries into:
Essentials
UI
Multimedia
Graphics
Data
Development
Utilities
Applications
It depends on what you really want. The first distinction that needs to be made is between a Javascript UI framework (which provides structure to the app), an HTML UI Framework (Presentation) and Widget Libs.
Javascript Frameworks such as backbone, angular, ember, and knockout provide MVC-like structure to the app.
UI frameworks such as YUI, bootstrap, and Foundation provide a consistent HTML and CSS base.
Widget Libraries such as jQuery UI, Fuel UX, and Kendo UI provide ready made widgets.
There are also fully-fledged frameworks which provide things across the board, such as Google Closure tools, Dojo with Dijit.
This Wikipedia list pretty much sums it up, and here is the comparison.
In order to find the best way to create a framework, first ask this question: Can any of the above frameworks/libraries solve all or some of the problems/requirements I have?
If something solves all the problems, you can use it right away.
If something solves your problem partially, you can start by extending/forking that project/framework.
Follow DRY and KISS rules. Only solve a problem which nobody has solved as of now.
Fortunately, there is already a good solution: Google Closure Library. This is what Google uses. It shows the approach of mixing HTML, CSS and JS. I wouldn't say it's perfect, but I believe it's one of the best ones at this moment. Its architectural principles rely on proven component based and OOP concepts, and it's accompanied with a static compiler for Javascript. It's definitely worth of studying before baking your own solution.
I'd like to say that cloudcoder2000's answer sums it up nicely. I'm just writing this answer because it didn't seem right in the comment section :P
If you are thinking of making another framework, my suggesting is to stop thinking.
First find the thing in current implementations which troubles you the most, and try to find how you can improve it. Contribute to existing projects, nearly all of them are open source anyways. Also, you don't really need to be a JS-ninja to get into their midst. Take a fork, and get started. Once you're done, and feel that you're code is good enough, make it known to the original repo's maintainers that you have done improvements, and are looking for it to be merged into the project.
Keep in mind here that I'm not discouraging you from solving the problem at all.
I'm just pointing out that there are so MANY frameworks out there, wouldn't it be better if you went ahead and contributed to one of them instead of going for complete glory and implementing a full framework yourself? Making a framework is hard, but getting people interested in your framework is HARD. Really Really HARD, even for Google! Only once Angular got a very good documentation (which itself took quite some time, and resources, of Angular evangelists), that it has gathered so much steam. So, I'm just saying that instead of creating your own monument, perhaps lending a hand to others would be a more worthwhile exercise.
Most importantly though, is the fact that since you are just starting out, I presume you wouldn't have much experience designing frameworks, or thinking in those design terms even. It would of immense value if you contribute to existing projects. Then you will be gathering knowledge and experience of how things are built. Then, you'll be more confident. Then, you can go ahead and make your own framework! Then you'll be more equipped to tackle mammoth projects such as designing a framework. And Then, my friend, will you make something which would be worth the time of countless developers.
Short answer
Build a skinny DOM and only focus on JS code to make it more efficient.
Long answer
A good architect always replies with "it depends." You can't have one single framework that enjoys all others' benefits and suffers from no disadvantages, all at once. There's always a trade-off.
In order to create a framework that is really lightweight, you would probably want the lightest DOM (HTML) structure. However, having a skinny DOM might have the cost of more JS code. So you would probably try to write the most efficient code. You can start here.
Needless to say, you should be keeping the open-close principle, and have the stylesheets separated from HTML, using only classes and never inline styling. I would suggest using less. It makes the implementation faster, and the result is pure css so you suffer from no performance issues around it.
I must respectfully disagree with cloudcoder2000,
From a young age I have been being told don't re-invent the wheel, but why?
During the last 3.5 years, I have re-invented almost all of my web controls using javascript/html/css. From the extremely complex; for example a grid, rich text editor, tree view, dialog. To the very simple, like a progress bar, dropdown. What I gained is a better understanding of html/js/css.
No pain, no gain. I'm so happy with what I was doing these years as I learned more than others.
Some of the controls I re-invented, I think, are much better than the popular ones, like telerik, jquery mobile, extJS. For example, my tree view is fully customizable, with it one can build very complex trees.
So, I encourage you re-invent the wheels, and you will definitely get more than you expected. But also, from the beginning, you need to learn the source code of the popular controls, and re-invent them. You will be very happy when you find yourself be able to make the controls better.
Then the tips on creating HTML controls:
1. use jquery;
2. write jquery plugins(jQuery.prototype...) for simple controls, while define classes for complex controls;
3. separate css from html and js files. Define the html template in js, don't use html files, which make using the controls hard.
Regards,
Leo
For best performance in your UI design, you need to use a lightweight JavaScript framework like angular or backbone, Twitter Bootstrap for the UI, AJAX for base script load and use gzip compression in your app to make it lightweight and help the UI render faster.

Is Knockout exclusively event driven?

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 :)

Other than data binding, what advantages does backbone.js (or knockout.js) offer

The JavaScript codebase we are using on our website is pretty well structured (outlined here if anyone's interested).
I have been looking at integrating backbone.js (or knockout.js, for some of the features) into our code -- but after closer considerations I don't think I care that much about data binding (my appliation does not do intensive client<->server data exchange, its more biased towards server->client->js data pipe), so I don't really care if I don't have dynamic data binding and syncing.
As I am not closely familiar with those libraries, I am afraid that by opting-out of using those libraries, I am missing some other vitally helpful features. Am I?
Personally I'd use backbone if I was building a full blown single-page web-app. If your website is primarily HTML, but uses JS for some minor added functionality I'd not worry about it. Backbone is good at handling client-side data models and tying changes to those to view updates.
Personally, I've used knockout and found it's reliance on data-binding in the HTML confusing. It wasn't something that worked well for me. It might be a little bit more friendly to building websites that are partially dynamic, because a lot of the logic goes right into the html view layer. You may want to listen to this recent podcast interview the creator of knockout as it may shed some light on things. http://javascriptjabber.com/
In my case, when building a big website with some dynamic elements I've stuck with the pattern of some global jQuery plugins and page specific JS. It works well enough for simple additions to specific pages.
I don't know if this question is super specific, so here's a generic answer :)
I'd first like to point out that while declarative databinding is the key feature for KnockoutJS, it is not a part of the core-backbone framework. There do exist multiple plugins like (Rivets.js and Orchestrator) which provide such functionality in Backbone JS.
Now coming to the primary aspect of your question - In terms of advantages other than Data-binding KnockoutJS does not have much to offer. However even if interactive data binding is not a primary concern you should definitely consider using BackboneJS. The reason for that is Backbone comes bundled with a client side routing system and a succinct but minimal approach towards managing Data obtained from the server in javascript.
As you have mentioned that your application is data-driven, probably the data that you have fetched in the client is not fetched all at once but is incrementally updated. In that scenario, having observable Models and collections might help you to manage your in-app data-dependencies well (as well as keep any widges for visualizing the data in sync.)

Categories

Resources