I know in dojo we can create any widgets in two ways,
To create widgets programmatically we'll use JavaScript, whereas for declaratively we'll use dojo attributes in HTML tags.
Can someone explain me what are the differences between them?
which one is mostly preferred and why?
Well, there are certain differences between both ways. In the declarative way, all configuration is based upon HTML attributes like dojo-data-props
but also some other attributes like the value, title, ... . So the DOM node you create actually serves as some kind of placeholder.
When you create widgets by writing JavaScript code, you will have to provide the DOM node you will attach it too, but the biggest difference is that it will not copy the HTML attributes from that DOM node. The DOM node here only serves as a container, not a placeholder.
There is no solution that is mostly preferred and it usually depends on the requirements of your application and what you think is the cleanest way of developing.
Personally I like the declarative markup because in the end it's a part of the user interface. However, you can go as far as you want. I've seen people creating stores and widget event handlers in a declarative way too, but I personally prefer to write them in JavaScript since they're not a part of the user interface.
There are also other reasons that might change the way you would create widgets. For example, one of the biggest drawbacks of declarative markup is that you need to parse the page (for example with parseOnLoad
). This usually is slower than creating the widgets programmatically. You can improve it by only parsing certain DOM nodes, but then you have to write additional code (and it still isn't faster).
Just a small note; this doesn't mean that the declarative way is slow. It's just an extra operation that should be executed and thus, it's a bit slower but chances are that the end user will not even see the difference.
An advantage of the declarative way however is that, when loading the page, the end user is able to see the placeholder. If you pick the right placeholder (for example, a <select>
for dijit/form/FilteringSelect
and dijit/form/ComboBox
), the end user will at least see something. If you create everything programmatically, the end user will see a blank page until the JavaScript code is executed.
So if performance is one of the requirements, then you could choose creating them programatically. If you like to have seperation of code where the presentation layer is seperated from the business logic, then I would recommend using the declarative way.
But in the end, both solutions are good.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With