Is Knockout.js inline with content/UI/behavior separation best practices? - html

I've been working on the web for quite a long time and I saw the "best practices" evolve. I'm now fairly convinced separating HTML (Content), Javascript (Behavior) and CSS (UI) is the best thing to do.
A few months ago, I started using knockout.js . I did choose it among other similar frameworks like backbone or angular because a chapter in an MVC training I followed was about knockout, and the concept seduced me. Then after a quick comparison on the web it didn't look as a bad choice for my needs, and for a start.
But here's my problem : when I look at my HTML code now, after a few weeks of dev on a project, there's quite a lot of knockout bindings in it, and it makes me think a lot about the old times, when we (or at least I) used to put inline javascript event handling through onclick attribute and so on.
Therefore those 2 questions, which I'm not sure are 100% suited for SO, but I can't find any better StackExchange site to ask it :
Is using knockout (or the other frameworks as they all seem to basically work with the same pattern) contrary to the "separation rule" ? Or is it an acceptable small-step-out of this rule ? or is it even perfectly acceptable because it uses the "data-" attributes ?
In the case this would be a somehow bad practice, is there any possibility to do all the binding through a separate javascript file, using for example jQuery to select the controls and apply bindings to them ? If not possible in knockout, is it with another framework ? I must admit at the time I did my selection, I diddn't think about this kind of implications...
Thank you and sorry if this should be moved to another SE site.

I had the same initial reservations as you, but I have to say that having the bindings in the html and not hidden away in a JS file seems so much better to me, as the link between presentation and functionality is now completely obvious. It massively reduces the possibility of changing some HTML and breaking functionality because you weren't aware that someone had hooked up some javascript to an element using jQuery.
Also, as you point out, the use of the data-bind attribute does, I think, mean that it does adhere to the separation rule, though if you want to stick to it rigidly then make sure all bindings are to observables, computed or functions on your view model, don't use any code (i.e. a visible binding that checks the state of two observables). I'm not sure I'd take it that far though.

I guess everyone started to learn KnockoutJS have the same concerns.
IMHO, there must be some way that connects models(JS object) with views(HTML markup). Then we should have something that says:"When that button is clicked call this function with that arguments." or "Hide this element while you that JS array is empty" and so on. So how we can put/say/state that connection in a readable, reusable and clean way.
If you used another JS file to handle that connection, then you 'll have large lines of code just to put your connection logic and you need to know how to select the DOM element you are targeting. You 'll end up with massive code(probably lot of jQuery) just to make your HTML dynamic and alive(i bet most developers got into that many times). I haven't use other libraries or frameworks but i think they just make your massive code more organized.
On the other hand by KnockoutJS use Declarative Bindings, this is the link between models and views. It's more readable, easy to plug it in/out and it allow you to just focus on writing a good JS model object.
I guess to truly check separation think what if you sometime needed to change your model, how much changes you need to do to your view? and vice versa?

Adding to the rest of the answers, some tips:
Make sure there's no business logic in your bindings. Any logic (which should be minimal) should be "view logic": decisions that only affect how your view looks, not how it works. Deciding how many items to display per screen is view logic; deciding whether the user can add another item is business logic. It's perfectly OK to put view logic in your viewmodel rather than your view, and it's desirable if it involves lengthy expressions.
Keep "magic numbers" out of any view logic in your bindings. If it's a parameter that could be changed (e.g. number of weeks of results to show) as opposed to a true constant (e.g. number of days in a week), make it a property of your viewmodel and reference it in any expressions in your views.

Related

When to use ng-view (with a router) or a custom directive to display templates(partials)?

I'm new to AngularJS and would definitely benefit from experient AngularJS developers! So here you go :
In AngularJS what is the difference in terms of performance of using ng-view (with router) or a custom directive to display templates (HTML partials) ?
How big should be a custom directive ? From what I see a custom directive could substitute a view entirely but should it be used that way ? There might be benefits and drawbacks using one or the other.
What would the be the rules of thumb to use one or the other ?
Many thanks in advance !
I think the performance aspect of the question is kinda a moot point. Let's use the idea of a table and a number of table rows. Unless you're generating 100s of rows of data utilizing custom directives or loading template, you're probably not going to incur any noticeable performance penalty. Angular caches templates so it's not like it's loading the same template over and over for each row. If you are generating large number of rows, then there are performance tweaks and different UX approaches you can utilize to address those issues (e.g. track by for ng-repeat, endless scroll, pagination, etc.)
How big should be a custom directive?
As you stated, you could use a directive to make an entire view. I think in Angular 1.*, that was not its intended functionality. A directive was more like a widget or UI Component (for those directives that are mostly UI containers with specific UX in mind, we're not considering non-UI type directives in this discussion obviously).
My rule of thumb is this:
If the UI in question has some ownership of a URL (aka. route) then treat it as a view. Generally a URL is unique visually speaking, so directive-ifing it will only create more work and little pay off.
If the UI in question works more like a widget/uicomponent, then use a directive.
If the UI in question is going to be reused over and over (e.g. inside ng-repeat) then a directive should be considered if isolating certain work on data it is consuming will be performed.
All of these points get complicated by the intended UX. But the rule of thumb provides a good starting point.
Keep in mind, Angular 2 is going to change all of this up by nixing scope and treating directives more like views.

jQuery Mobile page/navigation structure

I'm currently evaluating the combination of jQuery Mobile and PhoneGap. For my application, I need a kind of "inner application" navigation model: A fixed header that contains elements to switch between various contexts and functions, and the entire region below that depends on whatever function is selected. An example: The user selects a customer and can then switch between different data and statistics views concerning that customer. Alternatively, the user can switch between different customers while keeping the same view. Each function / view might again be a rather complex construct of multiple pages with its own navigation.
I think I understand the basic ideas of jQuery Mobile by now, but I'm unsure how to implement this "the right way".
I could do this simply by coding the entire header with the navigation into every single page, but that feels like a really bad idea - lots of redundant code, lots of places to insert tiny mistakes that are very hard to find.
I could try to add all the UI elements for the different views to a single page, hide them and only display the ones that belong to the current function. This doesn't feel right either - I suspect that the DOM would be really large and I suspect that this might cause various (performance) issues.
I could try to create the contents of the page that depend on the function dynamically using jQuery DOM manipulation techniques. This sounds like a good idea, but the individual pages can be really complex, and I'm worried that generating lots of complex HTML code using JavaScript will lead to an unmaintainable blob of code.
I could try to combine the approaches - code the individual pages in the HTML file and then somehow "link" them into the appropriate place using DOM manipulation - but I've never done that and I'm unsure if and how I can get this working.
I could try to put the "detail" page into an iframe - would this work at all?
What is the best / canonical way of implementing this kind of application? Do you know of any tutorials or examples?
Just detach your header and then reattach it to your new page. For instance:
$footer = $("#myfooter");
$header = $("#myheader");
$footer.detach();
$footer.appendTo('#newpage');
$header.detach();
$header.prependTo('#newpage');
$.mobile.changePage('#newpage');
Detaching does not kill all of your button handlers / etc. You will need to keep track of what page you are on or look at location.hash to do different things depending on what page is being shown.
--Greg Frame
Thex Interactive
www.thexinteractive.com
The first way is the easiest way to do it. That's the way i did it too. Also this gives u the freedom to add a button specific to whats in the browsing area for that page.
The second approach will have loads of extra calls which you don't want.
The rest of the approaches are not worth the effort.

Ajax versus Frames

In light of how ajax is actually used by most sites today; why is ajax embraced while frames are still regarded as a bad idea?
AJAX, from where I'm sitting, is a sort of grand tradeoff. You are breaking things in the "document" model of the interwebs so that your site can behave more like an "application." If a site is using AJAx well, they will break the document model in subtle ways that add something of value to the application. The "vote" link isn't really a link, but it gives you a cool animation and updates the question's status asynchronously.
Frames break just as much, if not more, of the document model (bookmarks, scrolling, copy-and-paste, etc) but without as much of the benefit. Frames also insert whatever decorations my OS/Window manager happens to be using, so they look pretty ugly.
AJAX, if done correctly, also breaks better for people using screen readers, text-based browsers, etc.
The big problems with frames are that it's possible to deep-link to the frames page outside of the frameset, and that bookmarking rarely works as expected. There are of course fixes for all these things, but they simply make an already not-very-nice system even clunkier and more complicated.
Ajax, as I have stated elsewhere, is more about bringing modern javascript to the mainstream and making it acceptable again than it is about using the xmlhttp object (which is really what the term AJAX means). Once you have a site on which javascript use is accepted and even expected, there's a lot more interesting stuff you can do with it.
With Ajax you can put all your logic in javascript code. That way you can create or use a javascript library that does not depend on your page. if you use an iframe, now you have to deal with a hidden control and most of your javascript code has to know the iframe.
Also for search engines work better if the page don't have frames.
Ajax gives you more granular control. You can update an individual element in a page, where Frames give you control of blocks that aren't even really in the same document.
Here are two simple answers:
1) Just using the term AJAX is cool and makes your project sound more "Web 2.0". Frames is not sexy. In fact, in web terms, frames are the antithesis of sexy.
2) AJAX is forward looking even if used in non-standard or poorly supported ways. It is less likely, IMHO, to break moving forward compared to frames which is backward looking even if in the same manner.
Ajax and frames are completely different from an accessibility standpoint (they're also completely different full stop).
Frames offer very little positive effect but bring with them a host of negative issues.
Ajax on the other hand makes the user interface more dynamic without compromising usability in most cases.

What are the "must have" features for a XML based GUI language

Summary for the impatient:
What I want to know is what you want to have in a new gui language. About the short answers mentioning $your_favorite_one; I assume you mean that, such a language should look like $your_favorite_one. These are not helpful. Resist the temptation.
I'm thinking on the user friendliness of XML based languages such as XHTML (or HTML, although not XML they are very similar), XUL, MXML and others ("others" in this context means that, I am aware of the existence of other languages and their implementations alternative to their original ones, and the purpose of the mentioning only these languages by name is, to give an idea of what I am talking about and I don't feel like mentioning any others and also, I see no point in trying to make a comprehensive list anyway.). I have some opinions about what features should such a language have;
The language should be "human writable" such that, an average developer should be able to code a good amount without constantly referring which tags have which properties, what is allowed inside what. XHTML/HTML is the best one in this regard.
There should be good collection of controls built-in for common tasks. XHTML/HTML just sucks here.
It should be able to be styled with css-like language (with respect to functionality). It should be easy to separate concerns about the structure and eye-candy. Layout algorithm of this combined whole should be simple and intuitive. Why the hell float removes the element from the layout? Why there is not a layout:not-included or something similar instead?
I know that I don't even mention very important design considerations like interaction with rendering engine and other general purpose languages, data binding, strict XML compliance (ability to define new tags? without namespaces?) but these are the points that I would like to ask what you consider important for such a language?
There will always be a tradeoff between ability and simplicity.
Personally I'm happy with the features of WPF (which uses XAML) for MS development. I dont find its complexity to be a barrier to developement at all.
However if your going to target your toolkit/language to a demographic that requires a higher degree of simplicity, you could possibly get away with leveraging an existing framework and provide the end user with a DSL specific to their needs.
Writing a new framework for the dev community as a whole is a mammoth undertaking though, and I suspect you will find that due to the wide range of features required that you will have to deal with a large degree of complexity at some point. Best of luck.
Most recent XML GUI language (not only for GUI actually) is called XAML. It has all that candies: styles, layout definition, objects initialization, etc. But it's a pain to write more or less large XAML files. Auto-completion helps but the core problem - forest of angle brackets - is not solved. Another problem with advanced XML-based GUI langs - they try to serve to several purposes at once, but XML syntax is not suitable for all situations. For example XAML supports data-binding, but why the hell I should write it in attribute string? It's first class feature and should have proper support.
IMO all modern XML-based langs suck terribly. Language intended for humans must not force it's users to write tons of brackets or do deep tags nesting. It must be user friendly, not computer friendly. My dream it to have GUI language with Python-like syntax.
In conclusion I want to say:
Dear XML-based langs authors, please be humane, don't create another language based on XML. Read some good book on Domain Specific Languages and please, don't make me type < and > symbols ever again.
You should have specified whether you mean web or rich client, but either way take a look at XAML/WPF. If you're anti-MS, then look at Moonlight, the Mono implementation of SilverLight.
I would like it to be easy to connect to any database, perform queries that return a recordset, and be able to parse and iterate easily said recordset to display its data in graphic controls, for example pie-charts, bar-charts, timeline charts (stock options like), node graphs with animation effects, all this at run time.
Easy mouse events catching, to implement any action on rollovers, mouseins, mouseouts, clicks, drag and drops, clipboard management, etc. A good infinite zooming capability would be great too.
I don't want to set a "datasource" that establishes a fixed connection between some column in my SQL query and some displayable element at design time, I want to perform any query that I want and show elements tied to any query field, anytime, in run time. I don't want to be only able to bind a datasource and displayable elements at design time.
css style capability for everything. Or something as simple and easy.
resize and layout taken care of automatically. Easy access to local files, to parse, play, display. Easy classes for image management, supporting transparency, resizing, etc. Basic and advanced classes for drawing in the screen: lineTo, rectangle, circle, animations. Even 3D.
Embedded fonts functionality. I don't want to worry about "will the user have this font installed?" Also I don't want to worry about DPI or screen resolutions.
Basic widgets: treeviews, etc.
A good designer. I don't want to add widgets writing the code. I want to place them visually in the screen.
Also, it would be good if it could connect to dlls made in C++ or COM objects in general.

Creating a web application, then adding Ajax to it?

I imagine there are many of you out there who have developed an application online which automates a lot of processes and saves people at your company time and money.
The question is, what are your experiences with developing that application, having it all set in place, then "spicing" it up with some Ajax, so it makes for a better user experience?
Also, what libraries would you suggest using when adding Ajax to an already-developed web application?
Lastly, what are some common processes you see in web applications that Ajax does well with? For example, auto-populating the search box as you type.
My preferred way of building Ajax-enabled applications is to build it the old-fashioned way where every button, link, etc. posts to the server, and then hijack all those button, link, etc. clicks to the Ajax functionality.
This ensures that my app is down-browser compatible, which is good.
It doesn't really matter which you use, unless you're trying to do something very specialized.
Here's a good list: http://code.google.com/apis/ajaxlibs/.
Yes, auto-completers are a pretty handy implementation of Ajax. It's also quite useful for data-intensive activities like populating drill-down data.
A lot of what you can do with these libraries isn't Ajax-specific, there is a lot of UI interaction that can benefit the user as well. You can do things like slideshows and lightboxes quite easily with many of these libraries.
Pick the one that you're comfortable with. The syntax they all use is a little different. Give a few a spin and try to build simple examples. Stick with the one you like.
Using ASP.NET Ajax to wrap a few chunks of code is an easy way to get going. But personally I prefer to use jQuery. You can easily add some simple Ajax calls with it to make the UI more responsive without the ASP.NET Ajax overhead.
If you are using ASP.NET to write your applications, adding AJAX using ASP.NET AJAX is very straightforward and in many places will not require you to change any code at all except add two controls to the pages you want to modify.
This works using partial page loads. The controls you have to add (off the top off my head) are called something like
<asp:ScriptManager
and
<asp:UpdatePanel
The biggest thing I use for AJAX is lists and search forms. Why? Because the overhead of loading an entire page when you are going though a list of, let's say, 200 records, it will get frustrating for a user to go though everything. However, it is important that if you click on a link in the page and then hit the back button or use a link at the top to return to the same page you were on.
For search forms, as you fill out the form I use AJAX queries to return the first few results and a number indicating how many records that were returned.
For AJAX frameworks, I use mootools. http://www.mootools.net.
Please ignore if not using ASP.NET. Your platform wasn't clear from your question.
Depending on when you created your web application, your web config file may need some tweaks to use ASP.NET Ajax. The easiest way to see is to create a new web site with the ASP.NET Ajax template and compare the web config, copying over configuration items as needed to bring the old one up to date.
If "spicing it up" is all you're after then develop the fully functional app without AJAX first. From here you can unobtrusively add AJAX functionality and ensure that the app degrades well for non JavaScript-enabled browsers.
I've started using jQuery for JavaScript on my site. It takes away all the worry of cross-browser JavaScript differences - things like class and classname, and getElementById. It also includes some very handy and simple functionality for AJAX postbacks. It's very easy to learn and extremely lightweight when used well.
I've seen some good use of AJAX right here on Stack Overflow, things like the tag selector and the question lookup when you type a question title. I think these simple things work best; we're just adding to the user experience with small additions to functionality that are intuitive, we're not flooding the screen with drag/drop handles etc.
I would differ from the first poster. Adding Ajax isn't always as easy as 1,2,3. It really depends on what you are after.
Adding things such as a colour animation can be made fairly easy, but if you are after things such as auto populating a text box, this requires extra code. It's not as easy as adding just something client side. You would also need to add in server-side support to fetch the partial query results.
Going beyond that, it can become even more complex keeping your client-side script in sync with server-side support.
But with the spirit of simplicity in mind there are libraries you can use to 'spice' up a website with animations and other eyecandy that can be implemented fairly easily which have been mentioned already.
I've often had to Ajax-enable an old-fashioned ASP.NET 2.0 sites. The easiest way I've found to do that is to create a new Ajax-enabled site and copy and paste certain sections of the web.config into your old project's web.config.
Just compare the two and see what's missing in your old one. You'll obviously also need to add references to AjaxExtensions and AjaxControlToolkit.