Substitute for querySelectorAll in Polymer - dart

Is there a substitute for querySelectorAll in Polymer?
I like to do many stuff programmatically and for single elements I use:
ButtonElement b2 = $["b2"];
But if I want to get several radiobuttons, I can't use the usual
List<InputElement> radios = querySelectorAll("[name='func']");
radios.forEach((f) {
f.onClick.listen((e) => changeFunction(f,e));
});
Should I be doing it in a different way?

ShadowRoot (which extends DocumentFragment), and Element both have querySelector and querySelectorAll that are scoped properly.
For a custom element, which you use depends on whether you want to query the light or shadow DOM, but since you are using $[], you probably want to use the shadow root.
Try this:
List<InputElement> radios = shadowRoot.querySelectorAll("[name='func']");

Related

how to access ShadowDOM of other polymer elements?

I'm learning Dart by making a simple webapp. the app ui I have in mind has two parts, one is a control panel, the other is a workspace. by clicking buttons in the control panel, user should be able to control the workspace.
both the control panel and the workspace are custom polymer elements. In the Control Panel's dart class, I can access itself by using shadowRoot.querySelector, but since the control panel needs to control the workspace, I need to access the workspace also. but I don't know how to do that. I tried querySelector for example, It gave me null. I understand it is a shadow DOM in the workspace tag, but how to access other tags' shadow DOM?
I can't find anything online, every example and document seems to only use shadowRoot to access self elements.
It is difficult to access the shadow DOM of another element, and this is by design. Instead of having your two custom elements so tightly coupled, a better approach would be to use events or signals. Your control panel element should take user input and fire appropriate events using the convenient fire() method it inherits from the PolymerElement class. Your application can catch and then relay those events to your workspace element. If that seems overly circuitous, you can use Polymer's <core-signals> element to pass events without dealing with intermediaries.
As an example, inside your control panel element, you might have a bold button.
<button on-click="{{boldClicked}}">Bold</button>
When that button is clicked, the control panel's boldClicked() method is executed in response. It might look something like this:
void boldClicked(Event event, var detail, Element target) {
fire('core-signal', detail: {'name': 'bold', 'data': null});
}
Then in your workspace element's HTML file, you might have:
<core-signals on-core-signal-bold="{{boldEventReceived}}"></core-signals>
And finally, in your workspace element's Dart class would be a method like so:
void boldEventReceived(Event event, var detail, Element sender) {
// manipulate workspace shadow DOM here
}
This is just one of several ways to accomplish this. You can look over the Dart team's <core-signals> example for more.
And of course, if you're using Polymer to its full potential, you will find that you need to do very little manual DOM manipulation. Using data binding and data-driven views is a winning strategy.
You can either use a selector that pierces though all shadow boundaries querySelector('my-tag /deep/ some-element') or querySelector('* /deep/ some-element') or as selector that just pierces through one level of shadow boundary querySelector('my-tag::shadow some-element') or alternatively
place both elements within the <template> of another Polymer element then you can connect attributes of both components with the same field on the common parent element (this is the preferred method in Polymer.
The solution of #user3216897 is fine of course especially if the elements don't share a common parent.
Instead of shadowRoot.querySelector you should be able to use $['abc'] if the element has an id attribute with the value 'abc'.

Rendering Polymer element once per multiple attribute changes

I have an Polymer.dart element with multiple attributes, e.g.
<code-mirror lines="{{lines}}" widgets="{{widgets}}">
</code-mirror>
on some occasions lines and widgets change simultaneously sometimes only widgets changes.
I would like to rerender component once independently on how many properties change in the same turn of event loop.
Is there a way a good built-in way to achieve that?
Additional trouble here is that interpretation of widgets depends on content of lines and ordering in which linesChanged and widgetsChanged callbacks arrive is browser dependent, e.g. on Firefox widgetsChanged arrives first before linesChanged and component enters inconsistent state if I do any state management in the linesChanged callback.
Right now I use an auxiliary class like this:
class Task {
final _callback;
var _task;
Task(this._callback);
schedule() {
if (_task == null) {
_task = new async.Timer(const Duration(milliseconds: 50), () {
_task = null;
_callback();
});
}
}
}
final renderTask = new Task(this._render);
linesChanged() => renderTask.schedule();
widgetsChanged() => renderTask.schedule();
but this looks pretty broken. Maybe my Polymer element is architectured incorrectly (i.e. I have two attributes with widgets depending on lines)?
*Changed methods are definitely the right way to approach the problem. However, you're trying to force synchronicity in an async delivery system. Generally we encourage folks to observe property changes and react to them and not rely on methods being called in a specific order.
One thing you could use is an observe block. In that way, you could define a single callback for the two properties and react accordingly:
http://www.polymer-project.org/docs/polymer/polymer.html#observeblock
Polymer's data binding system does the least amount of work possible to rerender DOM. With the addition of Object.observe(), it's even faster. I'd have to see more about your element to understand what needs rendering but you might be creating a premature optimization.
I think there are three possible solutions:
See this: http://jsbin.com/nilim/3/edit
Use an observe block with one callback for multiple attributes (the callback will only be called once)
Create an additional attribute (i.e. isRender) that is set by the other two attributes (lines and widgets). Add a ChangeWatcher (i.e. isRenderChanged() in which you call your expensive render method)
Specify a flag (i.e. autoUpdate) that can be set to true or false. When autoUpdate = false you have to call the render method manually. If it is set to true then render() will be called automatically.
The disadvantage of solution 1 is that you can only have one behavior for all observed attributes. Sometimes you want to do different things when you set a specific attribute (i.e. size) before you call render. That's not possible with solution 1.
I don't think there is a better way. You may omit the 50ms delay (just Timer.run(() {...});) as the job gets scheduled behind the ongoing property changes anyway (my experience, not 100% sure though)

Angular.Dart How to dynamically add Component to DOM?

I have a custom #NgComponent in my project and it works if I place it within the static HTML of the application. What I'm trying to figure out is how to add one to the DOM dynamically? If I construct an instance of my Component it does not appear to be of type Element and so it cannot be added directly to the children of an element in the DOM. Is there an alternate way to construct my component or wrap it for injection into the DOM?
e.g. I naively expected to be able to do something like:
dom.Element holderEl = dom.document.querySelector("#my-holder");
holderEl.children.add( new MyComponent() );
But I have also tried simply appending HTML containing my custom element to an element using innerHTML
holder.innerHtml="<my-component></my-component>"
and creating the element using document.createElement()
dom.Element el = dom.document.createElement("my-component");
dom.document.body.append(el);
But the component does not seem to be realized when added.
thanks,
Pat
You can add components dynamically, but you must manually invoke the Angular compiler so it notices that the innerHTML has a component embedded in it.
However, that is not the "Angular way".
Instead, write your template as
<div id="my-holder">
<my-component ng-if="should_component_be_displayed"></my-component>
</div>
Here, my-component will be created and included in the DOM only if should_component_be_displayed is true.
The my-holder div can be removed which leads to a cleaner DOM structure.

Whats the best way to get a Custom Element object for Conditional Elements

Using Polymer Dart I often need to get hold of the Polymer-Element object behind one of the child elements.
ButtonElement nextButton;
void inserted()
{
//Get hold of the elements
nextButton = shadowRoot.query('#nextButton');
//Do some thing useful with nextButton
}
<template if="{{emailValid}}">
<button id="nextButton" on-click="nextStep">
</template>
This works fine. However if in this case nextButton is underneath a conditional template its not part of the DOM when inserted() is called and is therefore not found. Is there anyway other way to get hold of it?
Otherwise I will have to some how determine when that conditional template is displayed and grab it then.
This might depend on what exactly "Do something useful with nextButton" means, but the Polymer-ic way to accomplish this is generally to encapsulate any reusable behavior together with the DOM it operates on. That is, instead of including code to operate on #nextButton in the enclosing element's inserted method, create a new custom element, let's call it super-button, and put the relevant code in super-button's ready or inserted method.
Then, if you find some behavior that really should be outside of super-button, follow the same pattern as the on-click handler you use above. Have super-button fire a custom event at the appropriate time and then declaratively map a handler to that event:
<template if="{{emailValid}}">
<super-button on-click="nextStep" on-my-special-event="mySpecialEventHandler"></super-button>
</template>

Determine if an element is a jQueryUI Widget

I have written a jquery-ui widget using the Widget Factory...
I need to be able to determine in code whether the element is already a widget or not...
My investmentGrid widget is created on #container with
$('#container').investmentGrid()
I need to be able to determine elsewhere in the code if $('#container') is already an investmentGrid
You can query the element's jQuery.data() function, like so:
if ($('#container').data('investmentGrid')) {
...
}
You could try the pseudo selector that is created for you when using the widget factory. $(":namespace-widgetname")
#dan-story may have had the answer at the time he answered it, but I have found that that method doesn't work anymore. Well, not entirely. At least not with jQueryUI 1.10. According to the documentation at http://api.jqueryui.com/jQuery.widget/ in the "Instance" section, you now need to have the widget's full name.
For example, if you create your widget factory with this:
$.widget("Boycs.investmentGrid", ...);
Then, to check if container has it, you would check with this:
if ($('#container').data('Boycs-investmentGrid'))
{
...
}
It is no longer enough to just use the name.
#Boycs: As per my understanding, using Widget Factory protects you from instantiating a plugin multiple times on the same element. (ref: http://jqueryui.pbworks.com/widget-factory)
In addition if you want to confirm if "container" is already an investment grid you can try the following option from inside your plugin code:
this.element.data("investmentGrid")
=== this;
For more details you can refer to docs.jquery.com/UI_Developer_Guide
Current versions of jQuery UI (I can confirm it with 1.11.x) allow you to query for an instance of a widget via the instance() method. This will then look like this:
$('#container').investmentGrid('instance')
If the element does not have an investmentGrid widget assigned, you will get undefined back.
You may also use call this instead:
$(#container').is(':data("namespace-investmentGrid")')
This has the advantage, that it also works even when the widget is not loaded.

Resources