Creating dojox/app Views Programmatically without HTML - javascript

I am thinking of making a web app and was contemplating using dojox/app to do it.
I would prefer to use a more programmatic approach to dojo but it seems dojox/app is mostly declarative.
After some searching I found an archive basically asking the same question I have
http://dojo-toolkit.33424.n3.nabble.com/Questions-about-dojox-app-design-td3988709.html
Hay guys,
I've been looking at the livedocs for dojox.app and while it seems quite cool I >have to say some stuff isn't clear to me.
Specifically, is the "template" property of views - specifying an html file - a >must or optional?
This was in 2012.
Since then I have found the customeApp test in the examples in the documentation which seems to show basic programmatic views in dojox/app however I am having some difficulty understanding it.
I would like to create the different views of my app like this
require([
"dojo/dom",
"dojo/ready",
"dojox/mobile/Heading",
"dojox/mobile/ToolBarButton"
], function(dom, ready, Heading, ToolBarButton){
ready(function(){
var heading = new Heading({
id: "viewHeading",
label: "World Clock"
});
heading.addChild(new ToolBarButton({label:"Edit"}));
var tb = new ToolBarButton({
icon:"mblDomButtonWhitePlus",
style:"float:right;"
});
tb.on("click", function(){ console.log('+ was clicked'); });
heading.addChild(tb);
heading.placeAt(document.body);
heading.startup();
});
});
but I can only find examples like this
<div data-dojo-type="dojox/mobile/Heading" data-dojo-props='label:"World Clock"'>
<span data-dojo-type="dojox/mobile/ToolBarButton">Edit</span>
<span data-dojo-type="dojox/mobile/ToolBarButton"
data-dojo-props='icon:"mblDomButtonWhitePlus"'
style="float:right;" onclick="console.log('+ was clicked')"></span>
</div>
Is there a way to go about this programmatically or somewhere I can find some clarification on whats happening here https://github.com/dmachi/dojox_application/tree/master/tests/customApp

Absolutely. I have been creating them programmatically for a long time and believe it is far superior way than templating. Difficulty in tackling a framework is knowing keywords to search for. Your answer, I believe, can be found by learning Dojo WidgetBase, and anything else that uses the word "Widget".
Good start is here http://dojotoolkit.org/reference-guide/1.10/quickstart/writingWidgets.html . To successfully work with Dojo Widgets you will also need:
concept of a LifeCycle http://dojotoolkit.org/reference-guide/1.10/dijit/_WidgetBase.html#id5. Lifecycle injection points will allow you to modify DOM tree of the template using JavaScript native API so you do not have to use data-dojo in attributes all over. You will capture nodes as private class properties during buildRendering phase so you can apply constructor parameters to them passed during instantiation in the parent. Finally, you will return the final DOM in postCreate() or startup(), depending on whether you need to specially handle child components or not.
concept of Evented http://dojotoolkit.org/reference-guide/1.10/dojo/Evented.html . This is what you need to do widgetInstance.on("someEvent", eventHandler) programmatically
Only custom attribute I use within an HTML tags of templateString is data-dojo-attach-point and data-dojo-attach-event. These are very convenient, saving lots of time and makes data binding less bug prone, to automatically connect widget's class properties with values in the tag. Although you can do those programmatically too with innerHTML, the amount of tedious boilerplate code in my opinion is not worth the effort.
Go through that tutorial and if by end you do not understand something do let me know and I will elaborate (I am not the type who just sends askers away on a link and not bother elaborate on the material).

Related

How to programmatically insert an Ember component into a div?

I am trying to figure out a way to use Ember components as a view template for tooltips. Let me explain this:
I am supposed to create a library to show tooltips in Ember. The content of this tooltip is unknown. It might be very complex or it might be a simple text. The developer is the one who will decide it but the library must offer a way to do it easily. Also, I want to offer this solution in the format of an Ember modifier so that the developer would code it something like:
<div {{tooltip foo bar}}>
Hello World
</div>
As the modifier offers a reference to its element it is easy to use the good old JS to create elements and append them to this element. For a simple text it works like a charm and I was able to do it already as shown in the example below, but for complex component it's better to create a component and show it inside the tooltip's container.
// tooltip.js
import { modifier } from 'ember-modifier';
import { isPresent } from '#ember/utils'
export default modifier(function tooltip(element) {
const content = document.createElement('span')
content.append('Hi, I am the tooltip\'s text')
element.append(content)
});
The problem starts when you want to build a complex view, specially if it's supposed to contain some logic associated.
What I thought is that I could programmatically insert Ember components into the element that is passed as the argument of the modifier function. I can't use the dynamic component helper ({{component}}) as it infers that I have to mess with .hbs files more than what I am doing already and I can't approach it using the tooltip as a component; I need it to be a modifier.
I looked into this solution here but it doesn't seem to work in Ember 3.8.
Can anybody give me a clue on how do make it happen?
I am using Ember 3.8 and Ember Modifier#1.0.5
You could use the same technique that either of these use:
https://github.com/NullVoxPopuli/ember-popperjs
https://github.com/CrowdStrike/ember-velcro
They allow for "any content tooltips" by using an external library (popper or floating-ui, depending -- these are important though, because positioning is hard).
The gist is the following:
modifier on the "reference" / "hook" element (what you hover over)
modifier on the "target" / "popover" / "loop" element
some code that communicates between the two modifiers to wait until both are present before rendering the tooltip in the correct location / position.
The key part missing from your original code is that you need two modifiers -- tooltips with complex content are not possible with a single modifier (unless you manually manage element references).
For ember 3.8, I don't know how much you'll be able to do.
Ember 3.28 is the oldest LTS supported now and is passed its last bugfixes date, and it will step receiving security patches in January -- see: https://emberjs.com/releases/lts/
you may be able to use 2 global modifiers and a service to communicate between them -- but I don't know how that would work when you attempt to have multiple tooltips / popovers on the screen at the same time.
The minimum ember version you need to use the two addons linked above is 3.27.
Personally, it's well worth the upgrade, as staying up to date is generally easier than leap frogging years at a time (because you have the community doing upgrades with you) -- and shiny stuff is fun :)

What is the correct way to set a div as the dropdown for a Dojo widget?

I asked a related question about this recently: Dojo _hasDropDown - How do I declaratively bind the properties?. However, I've been struggling with this problem for about 30 hours by now (20 of those before the last question), and I don't feel like I'm any closer. I'd normally edit the old question, but it would change the scope too much and invalidate existing answers.
My problem:
I have the following combobox and Memory store combined with a Struts2 request-scope servlet as part of machineOverview.jsp:
<div data-dojo-type="dojo/store/Memory"
data-dojo-id="machineNameStore"
data-dojo-props="<s:property value='%{getNameJsonString()}'/>"></div>
<s:set name="MachineName" value="machineSearchView.name"
scope="request"></s:set>
<div data-dojo-type="dijit/form/ComboBox"
data-dojo-props="store:machineNameStore, searchAttr:'name', value:'${MachineName}'"
name="machineSearchView.name" id="machineSearchView.name"></div>
I have this custom Dojo Widget in js/widgets/templates/ExpandableSearchComponent.html:
<div class="${baseClass}">
<div data-dojo-type="dijit/form/TextBox"
name="${SearchViewFieldName}TextBox"
class="${baseClass}TextBox"
data-dojo-props="placeholder:'${fieldName}'"></div>
<div class="${baseClass}Container" data-dojo-attach-point="containerNode"></div>
</div>
With this Javascript behind it in js/widgets/ExpandableSearchComponent.js:
/**
* Javascript for ExpandableSearchComponent
*/
define([ "dojo/_base/declare", "dijit/_WidgetBase", "dijit/_TemplatedMixin",
"dojo/text!./templates/ExpandableSearchComponent.html"],
function(declare, _WidgetBase, _TemplatedMixin, template) {
return declare("js/widgets/ExpandableSearchComponent", [ _WidgetBase,
_TemplatedMixin ], {
templateString : template,
SearchViewFieldName : "",
fieldName : ""
});
});
What I'm trying to do is essentially replace the first snippet with the below:
<div data-dojo-type="js/widgets/ExpandableSearchComponent"
data-dojo-props="SearchViewFieldName: 'machineSearchView.name', fieldName: 'Name:'">
<div data-dojo-type="dojo/store/Memory"
data-dojo-id="machineNameStore"
data-dojo-props="<s:property value='%{getNameJsonString()}'/>"></div>
<s:set name="MachineName" value="machineSearchView.name"
scope="request"></s:set>
<div data-dojo-type="dijit/form/ComboBox"
data-dojo-props="store:machineNameStore, searchAttr:'name', value:'${MachineName}'"
name="machineSearchView.name" id="machineSearchView.name"></div>
</div>
When this is done, it should just show a dijit/form/TextBox. When I click this Dijit Textbox, a dropdown should appear with in the dropdown the dojo/store/Memory and the dijit/form/ComboBox. Then, once the Combobox has had an option selected, both the Combobox and the dropdown should collapse again and the dijt/form/TextBox should show the value that was entered in the ComboBox, prefixed with the placeholder.
What I've tried:
I've tried a bunch of things:
I've tried binding _hasDropDown declaratively, which doesn't work.
I've tried binding it programmatically, during which I come into numerous problems with figuring out what to put in the define parameters, what to put in the function parameters, what to put in the declare parameters and what functions to return. I keep getting console errors in Chrome that are hard to figure out why they are happening, like my TextBox not being defined properly or my template Mixins not working properly,...
I've tried putting the original comboBox and Memory store into the widget directly, but I abandoned that path after 1 day because it was a fragile and complicated construction and it wasn't really what we wanted in the end either.
What I'm looking for:
I'm not looking for someone to implement this for me. I'm looking for a working example of using either dijit/_HasDropDown or dijit/popup used in a custom widget that includes:
The HTML of the widget;
The javascript code-behind of the widget;
How to use this widget in a page;
If necessary any related javascript for the page itself.
I've checked the Dojo documentation. There is no tutorial for either of the above dijit components. There is an API reference, but that only contains the Javascript, and even then just for how the API works.
The _HasDropDown Mixin API reference has the Javascript for how to add it to a widget, but not the HTML, and it shows how to create such a widget programmatically, but again without HTML code to explain what objects it is binding the widget to. It also uses Widgets, not a div, which I want to use for formatting reasons.
The dijit/popup API reference has the same issues as the _HasDropDown Mixin reference, meaning it shows the Javascript, but not the HTML or how to use it.
both of these API reference documents confuse me and I can't figure out how to implement them. I've also tried Googling, but most hits are for older versions of Dojo, from before the introduction of AMD modules.
As said a couple of times now, I can't figure out how to make these work. The documentation provided by Dojo explains part but not all of it and it's unclear to me how this all works. Can I even even use a widget in this manner? Will I have to write the textbox and the javascript to create the dropdowns directly into the source of my main page?
I'm hoping for a solution that allows me to just surround the element I want to convert with a div that has a data-dojo-type tag, so I have something semi-portable, but if that's not possible, I'll have to confer with my coworkers.
Clarification: I have read the sources for FilteringSelect, _HasDropDown, Select, ComboBox and some other Dojo components, but my big problem right now is that I can't figure out how they wire their dropDown to the right node.
Since you are looking for examples, have you checked the sources for the dijit widgets that use _HasDropDown? The documentation mentions Select, ComboBox, DropDownButton and DateTextBox. Their sources should give you a good sense for how to use the mixin, especially in conjunction with the reference pages explaining their use with programmatic and declarative examples.
For example the Select widget source: https://github.com/dojo/dijit/blob/1.10.6/form/Select.js and its reference page: http://dojotoolkit.org/reference-guide/1.10/dijit/form/Select.html
To make thing easier I suggest that you first refine the custom widget that must be dropped, programmaticaly place it as a normal widget and style it. It should then be very easy to use it as a drop down following the examples of the dijit widgets that use _HasDropDown.

Should all the view logic go in templates?

For example, I need to disable every input when the view's model isn't new (has an id).
I can do :
if(!view.model.isNew()) {
view.$('input, select, textarea').prop('disabled', true);
}
or I can go do an "if" on every input I have in my template:
<input type="text" {{# if model.id }}disabled{{/ if }}/>
If we follow the MVC (or MVP) pattern, I guess the second approach would be best, since the view logic is in the view. However, if I go with this approach and decide to change the condition that disables the inputs, I need to change it for every input in EVERY template. If I leave in the JS code, there is only one place to change.
This is just one example, but I am having similar dilemmas with alot of things. Hopefully you got an answer for that.
Cheers!
Based on your question, I'd say that you're probably running into this general problem for two related reasons -
You're using backbone exclusively, rather than a framework like Marionette or Chaplin.
Your views are "too big" and trying to incorporate too much material into a single view.
I almost never include logic into templates and that's because I almost never need to. That's because I write a lot of very small views, and piece them together to make large views. Marionette's view classes make this very easy to do, by subclassing the backbone view into different view types, adding additional utilities and drastically cutting down on boilerplate. Marionette is also very good at handling nested views, which really allow you to drill down and create the exact view tool you need for a specific use case.
It's not at all uncommon to be able to define a useful view using Marionette in 1-2 lines of code, which gives you a lot of flexibility to make very small, efficient views. The disadvantage to making lots of small views is that it's a lot of code to write, and could become difficult to maintain, but Marionette makes that disadvantage relatively insignificant. Marionette only took me a couple of days to get the hang of, and I highly recommend integrating it into your Backbone apps for exactly this problem.
When your views are big, and try to do too much, you wind up with the problem you're describing - you have to modify them too much to fit your specific needs and your code gets ugly and hard to read. When you have a lot of small views, they're very responsive and need little if any customization.
The example from your question is, I think, a border line case. My gut instinct would be to create two entirely separate views and run them under the following pseudo code:
editableView = { //definition }}
disabledView = { //definition }}
if (newModel)
editableView.render()
else
disabledView.render()
This is my gut instinct because my bet is that there are other differences between the views than whether the inputs are editable. Even if there aren't now, you may find in a few months that your needs have changed and that you'd like to incorporate some changes. The approach I suggest allows you to put those changes right into the appropriate View and not have to worry about logicking them out in a single view and deciding whether that logic belongs in the template or the view.
If you were absolutely certain that the only difference between the two views was going to be whether the inputs were editable, and that your needs are not going to change in the future, then maybe you would want to think about rendering them with the same view. If that is the case, I'd recommend that you put the logic in the javascript, rather than in the template, for the reasons you identified. But as I said, your example really is a borderline case, and in most instances I think you'll find that shrinking your view scope will really help you to see where your "template logic" belongs.
NOTE: I've talked a lot about Marionette in this answer, but I also mentioned Chaplin as another option above. I don't have much experience with Chaplin, but you may want to consider it at it as a Marionette alternative.
I prefer to do implement view logic in templates:
It is easier to change and read
Any dependency to id, element and etc can be implemented in template
List item
complex logic can be implemented in templateHelper of marionette or serializeData of Backbone without any dependencies to content of template or view
you can also implement complex logic using Handlebar Helper
Disadvantages of view logic in code are:
in case of changes to selectors (id, classes and so), all views have to be changed or reviewed
logic has to be applied again if view is re-rendered
Perhaps what you might be looking for presenter (aka decorator).
Instead of sending the template the model directly, consider sending it though a presenter, this way you can construct the attributes for the input field. Something like this:
present = function(model) {
return {
inputAttributes: model.isNew() ? 'disabled' : '',
id: model.id,
name: 'Foobar'
}
}
template(present(model));
then in your template:
<input type="text" {{inputAttributes}}>

attaching behavior to elements created by knockoutjs

Take, for example, the situation using knockoutjs:
<div id="container" data-bind="foreach:containers">
<li class="complex-element">...</li>
</div>
Now I want to attach some complex behavior to complex-element. How do I do that? I can't just attach events directly to complex-element, as they're created and removed dynamically at runtime to match the view model. So, as I see it:
I can riddle my html with data-bind="click:..."s and data-bind="mouseenter:..."s but I would rather avoid this if I could. Maybe I'm too rooted in my old MVC ways, but adding open(), select(), or dragStart() functions and isOpen, isSelected or isDragging observable flags to my view model just makes a mess and my intuition tells me that as the app gets bigger that view model is going to become unmanageable. I'd rather keep my data and my presentation separate if possible.
Or I can use jquery delegation to attach events to something that stays fixed. Something like:
$("#container").on('click', '.complex-element button.open', function(e) {
var elem = $(e.target).parents('.complex-element');
...
});
But this wouldn't work as the app gets more complex because what happens if the container is itself wrapped in an element only shown on login (<div id="wrapper" data-bind="if:isLoggedIn">...</div>). I might as well just bind all events to the body and that's a recipe for disaster.
I found a very cool article on knockmeout.net (http://www.knockmeout.net/2011/07/another-look-at-custom-bindings-for.html) that advocates using custom knockout bindings to drive complex behavior, and this seems to be an awesome solution for widget-like behaviors like autocompletes or date-pickers, but what about just simple old fashioned controllers... would this work?
I guess, after all that, my question is pretty simple: Has anyone used Knockoutjs on a really large web application? And how did you go about it?
You could use a different jquery bind:
$(document).on('click', '#container>.complex-element button.open', function(e) {
var elem = $(e.target).parents('.complex-element');
...
});
This would work if #container does not exist.
There is some work going on in the community to make the knockout bindings unobtrusive and easy to write. For now, knockout offers you dataFor() which can be seen here: Using unobtrusive event handlers or you can use a little library like this: Introducing the Knockout.Unobtrusive Plugin
If you need to execute some arbitrary js on some rendered elements from the foreach you could use the afterAdd callback
<div id="container" data-bind="foreach: { data: containers,
afterAdd: somefunction }">
<li class="complex-element">...</li>
</div>
I have used KO on a really large web app and the way I went about managing complexity was
Split out viewmodels into separate using namespaces within a single master namespace.
Write custom bindings for complex reusable behavior.
Created entity model classes that encapsulated most of the important business logic, akin to backbone models.
Ensured that the viewModels were entirely view specific and view related (helped by point 3)
Kept all jquery selectors to a bare minimum, I feel dirty writing any global delegates but sometimes they are needed.
Hope this helps.

OOPs concepts into Javascript widget

A simple javascript widget design question.
I have started working in javascript fairly recently. And as part of my work, I intend to create a lot of reusable code; so for me javascript widgets seems like the best way to go.
However I am faced with a design dilemma, and I am not able to find the right answer.
I have a simple javascript widget, which alters the string in a html component. So my widget is somewhat like this:
(function() {
var convertString = function() {
$(".classForHtmlComponentsIWantToHandle").each(function(index, element) {
//js_fu stuff done with string fetched from "element"
});
};
var _somePrivateHelperMethod() {
//some work that would have been impossible without this helper method
};
GloballyDefinedNamespace.StringUtils = {convert : convertString};
}());
this allows me to call later
GloballyDefinedNamespace.StringUtils.convert();
Now if you would notice in my widget-ish function above, I extract all the HTML components from the DOM, that I want to alter string for. Interesting bit is that HTML will have span and divs with same css class and also textbox components with css class.
Both have a different way of extracting their value and setting new value back.
Based on my experience, if this is a widget to alter string then all it should care about is incoming object that "hold" string in a uniform manner and then based on a object expectations, my widget should be able to operate blindly.
"if it sounds like a duck, walks like a duck, then it's a duck". Kind of thing.
So effectively I would like to be able to NOT worry about distinguishing "element" object being a textbox or span in my widget. Instead wrap it into a generic wrapper.
However people have advised me that in javascript widgets the usual convention is to take care of component specific stuff within widgets. I am not convinced, as I firmly believe in programming to interfaces and not specifics. So I am at conflict.
In my example above, I don't think so the highlighted dilemma does justice to this problem, but on a larger scale this pops up as a question for me often.
I would like to hear opinion from guys, as to how to build that component independence within my widget for an HTML DOM? Is a solution to create javascript wrapper objects with same interface and then css-select them separately and then make method call as following?
(function() {
var locateAllComponents = function() {
$(".generic-class").each(function(index, element) {
//wrap element into suitable wrapper that has common interface for getter
//setter.
GloballyDefinedNamespace.StringUtils.convert(wrappedElement);
});
};
}())
Any insights and answers would be highly appreciated.
You are trying to force concepts on javascript that are foreign to it.
Programming to an interface works for for OOP, but for other language types it is a bad idea.
You can look at how jquery uses .text() (http://api.jquery.com/text/) and .val() (http://api.jquery.com/val/) and you will see that what you want to abstract they put into two different functions, for a reason.
Widgets can be useful, but at a cost of bloat and performance, so you need to look at what you are doing and ensure that you don't exact too much of a price.
So, start small, perhaps with a widget that can work on form elements, and see what you can do reasonably within the object, but you will find that at some point it becomes very helpful if either the API user or the API developer creates functions to pass in to your widget, to get the additional functionality.
But, all of this will impact performance, so as you work, do some unit tests so you can look at changes in performance to help guide you on what changes are worth the price.
You may want to start with looking at the JQuery UI widgets though, and see what they did, rather than just re-inventing the wheel for no reason.

Categories