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 :)
Related
I am new to React js and I have been trying to understand what real problem does js frameworks like React,Angular solve and why one need to learn them.
Of Course when i see advantages of framework everybody talk about "Shadow/Virtual DOM, Router, Reusable Components etc" , but then I stumbled upon below links which talk something different
https://medium.com/dailyjs/the-deepest-reason-why-modern-javascript-frameworks-exist-933b86ebc445
https://www.codementor.io/binarymuse/react-components-from-a-jquery-programmer-background-du107k2lz
but they were not clear to me
So i am meaning to understand how difficult it was to maintain js/jquery code before these framework came by.
Everybody is just asking to learn these frameworks because they are popular but none of them clearly explains why they are popular and what problem they solve and how they make our life easier when it comes to creating web-app from scratch.
Others have already mentioned the advantages and what these frameworks resolve.
I wanted to add what problems they can create:
I have seen many people that use a framework see it as a hammer and every website as a nail. In other words they either don't or can't figure out that in many cases a framework is not needed. I have seen web pages that are nearly 90% static data still download an entire framework just to provide drop menus or something else trivial.
Frameworks force you into a lifecycle and development style that, in some ways, make some things easier and other things much, much more complicated. AngularJS had a nasty digest cycle that often led to complications. Redux forces you to write much more code than needed just to handle state that on many pages is not needed. Vue, React, Angular all force you to either use their data creation functions, their way of rendering or their way of handling inter element communication. And none of these are faster than vanillaJS. Even virtual DOM has its issues.
The size of a framework is often much more than needed. I have several small libraries that do the majority of the work that a framework does but my code is in the sub 5K range if I load it all.
Some people that learn a framework first can not figure out how to write in raw JavaScript. They also tend to learn sloppy ways to write code. No, not everyone, but a large number people that did not start with vanilla JS write code that tends to be much larger and sloppier than needed.
It is best to avoid JavaScript except where really needed. Often I can use raw HTML and CSS to do everything I need to do. I find that it is rare that I need to use much JavaScript even in projects that exceed several thousand files. It is faster to allow the browser to process HTML and CSS, which all processes at compiled speeds and only use JavaScript for things you can not do in HTML and CSS.
You don't "need" to learn them, but many people and companies use them. The main advantage is being able to have your entire site on a single webpage, where you just modify the data and it handles changing the elements on the page for you. For instance, you can just think about "put the user's name here, and when they click the button, add another list field there", but you no longer have to think about "get this DOM element, set its innerHTML to the user's name, and when they click the button, create a new DOM element for input, another one for the label, get the container element, append the new children". It also allows you to more easily bind data to DOM elements, so you can just say "this field is for the variable 'numberOfItems'" instead of worrying about grabbing the DOM element and its value and storing it into numberOfItems when you need it; with React/Angular/etc. that variable will always be up to date with the user's input without you needing to update it.
TL;DR: The frameworks are not necessary, but they help automatically handle a lot of common, tedious DOM manipulation for you in a way more optimized than you'd likely end up implementing yourself, with less code for you, and all on a single page instead of having to reload the page every time you want to display new data or a new layout.
What is React JS?
ReactJS is an open-source JavaScript library that is used for building user interfaces specifically for single-page applications. It’s used for handling the view layer for web and mobile apps. React also allows us to create reusable UI components.
React allows developers to create large web applications that can change data, without reloading the page. The main purpose of React is to be fast, scalable, and simple. It works only on user interfaces in the application. This corresponds to view in the MVC template. It can be used with a combination of other JavaScript libraries or frameworks, such as Angular JS in MVC.
https://www.c-sharpcorner.com/article/what-and-why-reactjs/
This is a wide discussion about frameworks in general. Is easy to say React, Angular and so on makes easier to manipulate DOM elements and reuse components, but to apply frameworks usually are about if solve your problem.
in javascript we have load the webpage by using location.href but by using angular/react we the page updates automatically.
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.
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".
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.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I am baffled by the difference in design between jQuery and Yahoo UI APIs. Disclaimer: I have a strong dislike of the jQuery api, but I am also a huge ignorant in web programming and javascript in general, so I could be dead wrong and come back here begging for redemption. so long...
The point of my question is the following. The two designs are different. jQuery puts the DOM at the center, and adorns the DOM by executing a "trigger" enhancer method on it. example
$("#flexigrid").flexigrid()
A requirement of jQuery is that you must, in some cases, follow a very specific conventional structure for your html beforehand. Example:
<div id="accordion">
<h3>First header</h3>
<div>First content</div>
<h3>Second header</h3>
<div>Second content</div>
</div>
and then
$("#accordion").accordion();
Moreover, the returned entity in general does not provide any mechanism to hide the DOM through a convenient programmatic method. To manipulate your jQuery entity you have to access the DOM via selectors, access that in some case is not guaranteed to be easy to know, like in the case of internally generated ids. Suppose that you want to swap the accordion programmatically, what you do is
$('#accordion').accordion('option', 'active', 2);
and not a more intuitive
myAccordion.setActiveTab(2);
On the other hand, yahoo ui focuses on javascript objects, you create them passing the DOM node selector (e.g. myDataTable = new YAHOO.widget.DataTable("container_id")) and then perform all manipulations through the object methods. Want to add a new row ? call myDataTable.addRow(). The DOM is hidden. You are not concerned with what's going on behind the scenes.
Now, my experience with Trolltech QT maps nicely to Yahoo UI. Clear, defined API of the widget objects, eventual freedom to reimplement part of them via inheritance, opaque rendering unless you want to open the box and get your hands dirty. QT is a winning API, works well, it's easy to use, and Yahoo UI is kind of similar in the design style. On the other hand, jQuery works in a counterintuitive (to me), very open box way, with reduced API on its objects.
Enough ranting. The point is that I assume I can be dead wrong on this, but I'd like to know why. What are the design advantages of having a jQuery-like interface (where the DOM is clearly exposed and you potentially have to hunt for stuff that jQuery plugins create automagically, so you can finally $(select) them and attach events or modify their content) instead of hiding everything behind an objects and commodity methods like YUI does ?
I'm not talking about speed, or code size, or amount of typing. I'm talking about design concepts like encapsulation, focus on interfaces, and ease of access. What design is better, in what situations, and why?
I don't think your argument is directed at jQuery, but more the APIs provided by plugin authors.
Unfortunately, no two plugin authors will create a plugin with the same API. The level of programmatic access is not limited by jQuery itself, but rather by the author/s of the plugin.
Also, as you said, jQuery is all about the DOM -- I see this as a benefit because it means jQuery doesn't get all mixed up in the "logic" (eh, "business logic") of the application... It's quite fine on it's own level of abstraction -- it deals with the DOM, and that's all!
You can create an unlimited amount of data structures and additional APIs for your application. jQuery doesn't hinder you in this respect.
You've added more details to your question -- this 'edit' is in response to those details.
I think what you're experiencing is common when you reach a certain stage with jQuery... The API becomes insufficient. You don't want the DOM... You want a nice clean API for your module, whether it's an accordion or a data-grid.
Personally, I don't think that some things should be bundled into a "jQuery plugin" -- doing so normally means sacrificing the API -- or having to resort to jQuery's mechanisms such as psuedo-event triggering through "trigger":
var someModule = $('#contain').someCoolModule();
someModule.trigger('initiate');
I get what you're saying, and I think I agree, but I also think it's important to have jQuery on an entirely separate level -- forget about it -- only utilise it when you need to attack the DOM.
jQuery doesn't require any kind of special markup - you can write a selector for any object. You can also use an existing DOM reference, and turn it into a jQuery object like so: $(domObject). Actually simpler and more capable than Yahoo UIs.
It's not required to know your dom selectors if you already have a DOM reference... That might be the source of your misunderstanding.
Having worked with both Yahoo UI and jQuery, let me tell you they are both great libraries. They're for different roles, but both have great approaches.
jQuery is kind of a wrapper, simplifying everything that has to do with the DOM, Ajax, selecting objects, doing graphics. It has a very concise and brilliantly simple API that abstracts all the browser compat nonsense away.
jQuery uses radically different design concepts than most newbie programmers are used to. It is really the poster child for how Javascript should be used. A few years back, there was a lot of ignorance about the power of Javascript. Mostly, because most of the javascript on the internet was terrible. Now, I think most people have realized that Javascript is one of the most capabable languages. It supports several paradigms: functional, imperative, object-oriented (prototype, not class-based), data literals....
jQuery uses Javascript to its full ability, using each aspect of its design to solve each problem in the most effective way.
I tell all people learning javascript to read the jQuery source over and over until they understand it.... It will be hard, but they will finish by being much better programmers, with a much larger assortment of tools in their toolbox.
It's kind of perpendicular to the Java/.NET brainwashing, which is to give every developer a screwdriver (OOP), and tell them it is the perfect soltion to every problem in programming and life.
Which, it's not. Every problem needs a different tool. OOP is good, but often a bad idea for some problems.
jQuery's mixin-style plugin architecture is really good. Different, but highly effective, fast, and easy to use.
jQuery is #1 for a reason - it's simple to use, and incredibly powerful.
Yahoo UI is a different approach, for a different problem. It's a UI toolkit that has very heavy abstraction from the DOM (vs. jQuery's lightweight approach).
You'll find yourself speding a lot of time modifying it if you intend to something outside the norm. (That's the downside of the heavyweight approach).
It's not a framework for developing apps. It's a bunch of GUI widgets.
I've used both together. There's no reason you can't use both jQuery and Yahoo UI on the same page, they're two different tools for different problems.
I suggest including jQuery site/app-wide, then including jQuery UI plugins as needed. If you need heavyweight stuff, add Yahoo UI. But stick to jQuery for your plumbing code...
Learn from jQuery. Understand the power of array programming, callbacks, data literals, treating code as data, and keeping things concise. And that using the right tool for each problem means much shorter, simpler code.
In my opinion, YUI is weaker in DOM manipulation, but is way ahead in design.
JQuery is designed for those with little or no JavaScript (or general coding) experience. Its very easy to get an application up and running.
YUI is more readable, and any programmer can pick it up and go very quickly because of the wide use of best-practice methodologies.
jQuery is a great library for DOM manipulations, and centering it's API around selectors is one of the reasons why it's so popular today. The thing is, jQuery wouldn't be needed if the browsers DOM APIs were more consistent and easier to use. And I agree with Robert Harvey (commented above) that as an abstract layer over the DOM jQuery does a very capable job.
But as I understand, you dislike jQuery plugin system and the jQuery UI, not the core library itself. Personally, I prefer a YUI style API for components and widgets, because at the higher abstraction level DOM elements become less important. I think the reason why jQuery UI authors chose this design is to make API more consistent with their main product, jQuery library. But I don't agree that this was a good decision.
jQuery is designed to work with the DOM (i.e. it's a language highly optimised around web pages).
you potentially have to hunt for stuff that jQuery plugins create automagically
Presumably if it's appropriate, a plugin returns a jQuery object that you can manipulate, unless it's badly written. In which case that's obviously the plugin's fault.
If you're using a method that autogenerates IDs then jQuery may not be for you. However for example I've used jQuery with Google Maps without too much trouble.
If you wanted to add a row to a table automatically, I'm sure there's a plugin out there. If not, it wouldn't take much to write one.
I agree with Computer Linguist. OOP is not a perfect fit for every possible for problem.
In case of web development one first has to decide upon the kind of solution that one has to design. Is the solution essentially a web page with interactive widgets embedded at places that enhance the interactivity or is it a full fledged RIA. JQuery,I believe is fit for the first case and it is basically targeted towards ease of handling of the DOM.
In case of RIA applications, toolkits working at a higher level of abstraction are prefered because the developer in this case is dealing with widgets and layouts rather than the HTML and css that lies underneath. In such case using Object Oriented Toolkits like YUI, Dojo or ExtJS are more convenient as they bring the desktop application development approach (with its associated advantages) to the web domain.