Dojo NodeList-traverse - order of nodes returned - dojo

HTML
<div id="outer-container" class="container">
<div id="inner-container" class="container">
<div id="some-node"></div>
</div>
</div>
JS
require(["dojo/query", "dojo/NodeList-traverse"], function(query){
console.log(query("#some-node").parents('.container'));
});
This will log an array with two DOM nodes - the one with the id "outer-container", and the one with the id "inner-container".
What I want to know is, is there a way to know in what order will parent nodes appear in the array returned? My testing showed that there isn't, but that doesn't make sense, the method goes through the DOM structure either upwards or downwards, right?

I tested your code in JSFiddle and always got the same result:
[div#inner-container.container, div#outer-container.container]
If you really want to know what happens, check the "dojo/Nodelist-traverse" class in the Dojo source.
This is what the "parents()" method does:
parents: function(/*String?*/ query){
return this._getRelatedUniqueNodes(query, function(node, ary){
var pary = [];
while(node.parentNode){
node = node.parentNode;
pary.push(node);
}
return pary;
}); // dojo/NodeList
}
I haven't gone through the "_getRelatedUniqueNodes" method, but it seems that the "closest" parent is added to the list first, following it's parent .... and so on. This is exactly what happened in my JSFiddle.

Related

How to change contents of a virtual dom element in Mithril?

How do I access a virtual dom element to change its contents using Mithril? I am new to Mithril and still trying to figure things out. For example, I want to access the third div with id "three" and change it's contents to "Blue Jays" without touching any of the other div's.
Thanks.
<div id='main'>
<div id='one'>Yankees</div><br>
<div id='two'>Red Sox</div><br>
<div id='three'>Orioles</div>
</div>
In mithril, like in react/vue/angular, you dont act on the actual DOM directly. Instead, you define the outcome that you want, so for example, to render the DOM tree that you posted you would do something like this:
var my_view = {
view: vnode => m('div#main', [
m('div#one', 'Yankees'),
m('div#two', 'Red Sox'),
m('div#three', 'Orioles')
])
}
m.mount(root, my_view)
<script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/2.0.4/mithril.js"></script>
<div id="root"></div>
the m(...) functions inside the array have a string as their second argument, that makes the output static, but we can change that to a variable:
var my_view = {
oninit: vnode => vnode.state.fave_team = 'Orioles',
view: vnode => m('div#main', [
m('div#one', 'Yankees'),
m('div#two', 'Red Sox'),
m('div#three', vnode.state.fave_team)
])
}
m.mount(root, my_view)
<script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/2.0.4/mithril.js"></script>
<div id="root">
</div>
In this case I used the state property of the vnode argument, but you can also use a third party state manager like flux or any other.
Now that we have it as a variable, it will show the current value on every call m.redraw(), most of the times we dont have to do this call ourselves, for example:
var my_view = {
oninit: vnode => {
vnode.state.fave_team = 'Orioles'
},
view: vnode => m('div#main', [
m('div#one', 'Yankees'),
m('div#two', 'Red Sox'),
m('div#three', vnode.state.fave_team),
m('button', { onclick: () => vnode.state.fave_team = 'Dodgers' }, 'Change')
])
}
m.mount(root, my_view)
<script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/2.0.4/mithril.js"></script>
<div id="root"></div>
And thats it, any dynamic content in your DOM elements you set it as a variable/property in an object.
One of the beautiful things about mithril is that it doesnt force you to do things one specific way, so if you really want to work on the actual DOM node, there are lifecycle events that you can attach to any virtual node ("vnode")
You can easily capture the HTMLElement (i.e., HTMLInputElement) with the Mithril Lifecycle event of oncreate(). This is an actual example from my code (in TypeScript) where I need to hook up a few event listneres after the canvas element was created and its underlying DOM is available to me at "raw" HTML level. Once you get a hold of dom, then I manipulate that element directly. Many people think that why not use oninit(), but oninit() is before the generation of dom, so you will not get the element back at that stage.
Now, if you just do that, you will likely be posting another question - "Why the browser views not updating?" And that's because you do have to manually do a m.redraw() in your event handlers. Otherwise Mithril would not know when the view diffs to be computed.
const canvas = m(`.row[tabIndex=${my.tabIndex}]`, {
oncreate: (element: VnodeDOM<any, any>) => {
const dom = element.dom;
dom.addEventListener("wheel", my.eventWheel, false);
dom.addEventListener("keydown", my.eventKeyDown, false);
}
},

Aurelia: Deleting array elements when changed to empty value

I have an array of strings bound to input elements:
<div repeat.for="i of messages.length">
<input type="text" value.bind="$parent.messages[i]">
</div>
I need to delete an element when the input content is deleted, without using dirty-checking.
This sounds easy - just delete the element which has empty value from the input.delegate handler, unfortunately this does not work due to an Aurelia bug #527. Here's a gist that tries this approach: https://gist.run/?id=e49828b236d979450ce54f0006d0fa0a
I tried to work around the bug by using queueTask to postpone deleting the array element, to no avail. And since the devs closed the bug because according to them it is a duplicate of a completely unrelated issue I guess it is not getting fixed anytime soon.
I am out of ideas how to implement this, so any suggestions are welcome.
Absolutely no need for any kind of dirty checking here! :)
Here's a working demo for your scenario: https://gist.run/?id=20d92afa1dd360614147fd381931cb17
$parent isn't needed anymore. It was related to pre-1.0 Aurelia versions.
If you use a variable instead of array indexes, you can leverage two-way data-binding provided by the input.
<template>
<div repeat.for="msg of messages">
<input type="text" value.bind="msg" input.delegate="onMessageChanged(msg, $index)">
</div>
</template>
So, your onChange event could be simplified like this:
msg holds the actual value of your current input.
i index will be used for deletion.
export class App {
messages = ['Alpha','Bravo','Charlie','Delta','Echo'];
onMessageChanged(msg, i){
if (!msg || msg.length === 0) {
this.messages.splice(i, 1);
}
}
}
There was a related question about a similar problem. This answer might give you more details about the main idea.
Ok, so the solution to this is not to use the buggy (in this case) aurelia 2-way binding, but to use 1-way binding and set the value from the input.delegate handler:
https://gist.run/?id=2323c09ec9da989eed21534f177bf5a8
The #marton answer seems to work at first sight, but it actually disables 2-way binding, so any changes to the inputs are not copied to the array. But it gave me an important hint how to solve the issue.
The equivalent of this html code:
<div repeat.for="msg of messages">
<input type="text" value.bind="msg">
</div>
is this:
for (let msg of messages) {
msg = 'something else'; // note: this does not change the contents of the array
}
See issue #444 for more details
Hence, this forces one-way binding. To fix this in the #marton solution, we only have to change the value from the input.delegate handler:
onMessageChanged(msg, i){
if (!msg || msg.length === 0) {
this.messages.splice(i, 1);//delete the element
}
else {
this.messages[i] = msg;//change the value
}
}

Dojo1.9: Custom widget inherited from another custom widget template string update not reflected

I have a custom widget which extends _WidgetBase, _TemplatedMixin with template
<div dojoAttachPoint="widget">
<div dojoAttachPoint="title">${name}</div>
<div dojoAttachPoint="dnmschart"></div>
</div>
and another widget which extends above widget
require([
'dojo/_base/declare',
'my/widget/view/AbstractWidget'
], function (declare, AbstractWidget) {
return declare("my.widget.view.AbstractChart", [AbstractWidget], {
constructor:function(){
},
buildRendering: function(){
this.inherited(arguments);
var gridDiv = document.createElement("div");
gridDiv.setAttribute("dojoAttachPoint", "gridPlaceHolder");
},
postCreate:function(){
this.inherited(arguments);
//Here I could not get newly created node gridPlaceHolder
console.log(" POST CREATION");
}
});
});
When I print in console (Break point in post create method)
this.domNode
It shows newly created node at last in document(last node in above template)
<div dojoattachpoint="gridPlaceHolder"></div>
But I could not access gridPlaceHolder attach point in post create method.
Is there anything else need to configure?
Please help me on this:)
data-dojo-attach-point (which you should use for 1.6+ instead of dojoAttachPoint) allows you to have handles for dom nodes in your template.. It is parsed by _TemplatedMixin's buildRendering(), so it will be available in your buildRendering method just after this.inherited line.
You can not set data-dojo-attach-point using setAttribute, it can only be defined in templates to be parsed by TemplatedMixin. If you need your child widget to add some markup in addition to what there is in its parent's template, you can define a variable in your parent's markup, and overwrite it in your child widget:
Your AbstractWidget template:
<div data-dojo-attach-point="widget">
<div data-dojo-attach-point="title">${name}</div>
<div data-dojo-attach-point="dnmschart"></div>
${childMarkup}
</div>
And then you need to add your additional markup in child's buildRendering, before this.inherited:
require([
'dojo/_base/declare',
'my/widget/view/AbstractWidget'
], function (declare, AbstractWidget) {
return declare("my.widget.view.AbstractChart", [AbstractWidget], {
buildRendering: function(){
this.childMarkup = '<div data-dojo-attach-point="gridPlaceHolder"></div>';
this.inherited(arguments);
}
});
As stafamus said, the primary problem here is that you're attempting to assign data-dojo-attach-point or dojoAttachPoint to a node after the template has already been parsed (which happens during the this.inherited call in your buildRendering.
Going beyond that, given the code in the original post, it also appears you're never actually adding the markup you create in buildRendering to your widget's DOM at all - you've only created a div that is not attached to any existing DOM tree. I'm a bit confused on this point though, since you claim that you are seeing the markup for the node you added, which shouldn't be possible with the code above, or the code in stafamus' answer.
Rather than attempting to dump extra markup into your template, you might as well do the programmatic equivalent to what an attach point would be doing in this case anyway: create your DOM node, attach it to your widget's DOM, and assign it to this.gridPlaceHolder. e.g.:
buildRendering: function () {
this.inherited(arguments);
this.gridPlaceHolder = document.createElement('div');
this.domNode.appendChild(this.gridPlaceholder);
}

Is there a way to disconnect an event added by dojoAttachEvent

I have a dojo widget which uses a a custom-library code having a link like this in its template.
Go Back
I need to find a way to disconnect this event from my widget. The only way i know how an event can be disconnected is, using a
dojo.disconnect(handle)
I could use this if I had the event connected using dojo,connect() which returns me the handle.
However with dojoAttachEvent i don't have the event handle hence no way to disconnect it.
Note :
Changing this html is not an option for me, since this an external library i am using.
Also, I am not looking for a solution to disconnect all events.
CODE:
otherWidget.js:
dojo.provide("otherWidget");
dojo.declare("otherWidget", [], {
templateString : dojo.cache("otherWidget","templates/otherWidget.html"),
_goBack: function(){
this.destroyWidgetAndRedirect();
},
destroyWidgetAndRedirect: function(){
//Code to destory and redirect.
},
});
otherWidget.html:
<div>
Go Back
<!-- Other Widget related code -->
...
</div>
myWidget.js:
dojo.provide("myWidget");
dojo.require("otherWidget");
dojo.declare("myWidget", [], {
templateString : dojo.cache("myWidget","templates/myWidget.html"),
this.otherWidget = new otherWidget({}, dojo.byId('otherWidgetContainer'));
});
myWidget.html:
<div>
<div id="otherWidgetContainer"></div>
<!-- My Widget related code -->
...
</div>
Any thoughts..
Thanks.
Extension points can be used directly on your html, or in javascript. Suppose the widget you are using is called 'my.custom.dojowidget', and that it has an onClick extension point. I will show here the declarative way, in your html. Try this :
<div data-dojo-type="my.custom.widget">
<script type="dojo/method" data-dojo-event="onClick" data-dojo-args"evt">
dojo.stopEvent(evt);
console.debug("did this work ?");
</script>
</div>
Now this depends on the existence of the extension point... if you can't still do what you want, please post the relevant parts of your widget's code.
So... based on the sample code you posted in your edit, I think you should do the following :
<div data-dojo-type="otherWidget">
<script type="dojo/method" data-dojo-event="destroyWidgetAndRedirect" data-dojo-args="evt">
dojo.stopEvent(evt);
// do whatever custom code you want here...
</script>
</div>

Dojo Issue: .parent() not a function

The HTML snippet:
<div class="hide_on_start">
<label>Type of Visit</label>
<div id="record_visit_type"></div>
</div>
<div class="hide_on_start">
<label>Visit Date</label>
<div id="record_visit_date"></div>
</div>
<div class="hide_on_start">
<label>Staff</label>
<div id="record_staff"></div>
</div>
The javascript I am using:
>>> dojo.byId('record_visit_type')
<div id="record_visit_type">
>>> dojo.byId('record_visit_type').parent().removeClass('hide_on_start')
TypeError: dojo.byId("record_visit_type").parent is not a function
I don't understand what the issue is with dojo.byId('record_visit_type').parent().removeClass('hide_on_start'). Can somebody explain?
Thanks
It looks like you're using dojo.byId as if it returns a dojo.NodeList, but it doesn't - it just returns a DOM node. Only dojo.query regularly returns dojo.NodeList objects.
dojo.NodeList objects have a removeClass function (which operates on all nodes in the list), and if you dojo.require("dojo.NodeList-traverse"), they also have a parent() function which returns a new NodeList containing the immediate parents of respective nodes in the original list.
http://dojotoolkit.org/reference-guide/dojo/NodeList-traverse.html
Theres a couple of problems I see with your code:
I think what you are looking for is the parentNode property of the domNode you are retrieving. This is not a method, but a property of the domNode you are looking up via dojo.byId.
Also, domNodes themselves to not have a removeClass method. You probably want to use dojo's dojo.removeClass(domNOde, cssClass) method to do this.
var recordVisitTypeDomNode = dojo.byId('record_visit_type');
dojo.removeClass(recordVisitTypeDomNode.parentNode, 'hide_on_start');
parentNode is right but here is how you do it in dojo:
// Go from the DOM node to a NodeList
var myDomNode = dojo.byId('record_visit_type');
var myNodeList = dojo.query(myDomNode);
// Get the parent
dojo.require("dojo.NodeList-traverse");
var parent = myNodeList.parent()[0];
This method of calling dojo.query is valid:
// Non-selector Queries:
// ---------------------
//
// If something other than a String is passed for the query,
// `dojo.query` will return a new `dojo.NodeList` instance
// constructed from that parameter alone and all further
// processing will stop. This means that if you have a reference
// to a node or NodeList, you can quickly construct a new NodeList
// from the original by calling `dojo.query(node)` or
// `dojo.query(list)`.
http://jsapi.info/dojo/1/dojo.query
It is like jquery $(myDomNode).parent().