How do I programatically select and disable a PaperButton? - dart

I'm trying to migrate from Bootstrap to Polymer/Paper and I've got a lot of situations where I have to enable/disable buttons that were previously accessed as ButtonElements and then .disabled=true/false.
So for example I've got a paper button I'm trying to access and enable/disable via querySelector as such:
PaperButton nextWeekButton = querySelector("#nextweekbutton");
nextWeekButton.disabled=!_status;
But I am getting the error: type 'HtmlElement' is not a subtype of type 'PaperButton' of 'nextWeekButton'.
I get the same variety of message if I try as an InputElement or ButtonElement. If I try to get it as an HtmlElement then of course I get the "setter 'disabled' is not defined..."
I was going to start playing around with attribute setting but really shouldn't there be a way to do this that's like the ButtonElement? Just want to make sure I am not missing anything.
Update: For now I am doing this
void disableButton(Element _e, bool _status) {
if(!_status) {
_e.setAttribute("disabled","true");
} else {
_e.attributes.remove("disabled");
}
}

I'm pretty sure the problem is that your code is executed before Polymer is initialized. See https://stackoverflow.com/a/20982658/217408 how to initialize Polymer when you have a custom main method.

Related

if the original JS has many functions, how dart to initiate them?

after several rounds of research, I found there is no clear answer about the situation like below:
I have a js file called 'AAA.js', and there is simple code in side like this:
var AAA = {
listenForMenuLayer: function () {
console.log("menu initiated");
$('.nav-menu').on('click', function() { console.log("menu clicked")});
}
init: function(){
this.listenForMenuLayer();
}
};
And in the dart, I wrote like below (using 'dart:js'):
js.context['AAA'].callMethod('init');
Then, when I run it, everything looks fine, the "menu initiated" shows properly, which means the 'listenForMenuLayer' is initiated, but when click on the '.nav-menu', there is nothing happened. (I check many times, there is no spelling error or else)
My question is: Can Dart accept this kind of initiating of external JS event? or we should re-write those JS events at all, please advise, many thanks.
Updates:
I found that if we write the js code like above, the jquery will not be initiated properly, which means all the features begin with '$' will not be functional.
guys, I update it to using 'package:js/js.dart';
#JS('AAA.init')
external void aInit();
then some where, just simply call after including:
aInit();

Listening to JS CustomEvent in Dart

I know that my question is not new, but all solutions I've found here and in the Internet are not working :( Or, I'm doing something completely wrong.
I need to create a communication between Dart and JS, and I would love to use events, as the idea seems to be neat and simple.
So, I tried this tutorial: https://dart.academy/easy-dart-js-interopt/
My JS code:
var customEvent = new CustomEvent("fromJavascriptToDart");
window.onload = document.dispatchEvent(customEvent);
document.addEventListener("fromJavascriptToDart", test, false);
function test() {
console.log("Listening");
}
The event is dispatched, as I see Listening in console log.
But when it comes to dart, nothing is working.
I've tried the following methods and everything failed:
document.on['fromJavascriptToDart'].listen((CustomEvent event) {
print("HEY! I'M LISTENING!");
});
window.on["fromJavascriptToDart"].listen((e) => print( "HEY! I'M LISTENING!"));
window.on['foo'].add((e) => print(e.detail)); //This is not working, as there is no add method in Stream Event anymore
#Listen('fromJavascriptToDart')
void eventTest(){
print("HEY! I'M LISTENING!");
}
Any help is mostly appreciated.
DartPad example
document.on['fromJavascriptToDart'].listen((CustomEvent event) {
print("HEY! I'M LISTENING!");
});
Works fine.
#Listen() is Polymer specific
add doesn't exist (listen as show above should be used)
the event doesn't seem to reach window, but I'm sure this will behave the same in pure JS.

How to query for an element inside a dom-repeat

I have been scouring the web for a clear answer on how to query for an element generated by a dom-repeat element from Dart code.
sample.html
<dom-module id="so-sample>
<style>...</style>
<template>
<template is="dom-repeat" items="[[cars]] as="car>
...
<paper-button on-click="buttonClicked">Button</paper-button>
<paper-dialog id="dialog">
<h2>Title</h2>
</paper-dialog>
</template>
</template>
sample.dart
I'll omit the boilerplate code here, such as imports or the query to my database to fill the cars property ; everything works fine.
...
#reflectable
void buttonClicked(e, [_])
{
PaperDialog infos = this.shadowRoot.querySelector("#dialog");
infos.open();
}
This generates the following error :
Uncaught TypeError: Cannot read property 'querySelector' of undefined
I have tried several 'solutions', which are not, since nothing works.
The only thing I saw on quite a lot of threads is to use Timer.run() and write my code in the callback, but that seems like a hack. Why would I need a timer ?
I understand my problem may be that the content of the dom-repeat is generated lazily, and I query the items 'before' they are added to the local DOM.
Another advice I didn't follow is to use Mutation Observers. I read in the polymer API documentation that the observeNodes method should be used instead, as it internally uses MO to handle indexing the elements, but it again seems a bit complicated just to open a dialog.
My final objective is to bind the button of each generated model to a dedicated paper-dialog to display additional information on the item.
Has anyone ever done that ? (I should hope so :p)
Thanks for your time !
Update 1:
After reading Gunter's advices, although none of them actually worked by themselves, the fact that the IDs aren't mangled inside a dom-repeat made me think and query paper-dialog instead of the id itself, and now my dialog pops up !
sample.dart:
PaperDialog infos = Polymer.dom(root).querySelector("paper-dialog");
infos.open();
I now hope that each button will call the associated dialog, since I'll bind data inside the dialog relative to the item I clicked ~
Update 2:
So, nope, the data binding didn't work as expected: All buttons were bound to the item at index 0, just as I feared. I tried several ways to query the correct paper-dialog but nothing worked. The only 'workaround' I found is to query all the paper-dialog into a list and then get the 'index-th' element from that list.
#reflectable
void buttonClicked(e, [_])
{
var model = new DomRepeatModel.fromEvent(e);
List<PaperDialog> dialogs = Polymer.dom(this.root).querySelectorAll("paper-dialog");
dialogs[model.index].open();
}
This code definitely works, but it feels kind of a waste of resources to get all the elements when you really only need one and you already know which one.
So yeah, my initial problem is solved, but I still wonder why I couldn't query the dialogs from their id:
...
<paper-dialog id="dialog-[[index]]">
...
</paper-dialog>
#reflectable
void buttonClicked(e, [_])
{
var model = new DomRepeatModel.fromEvent(e);
PaperDialog dialog = Polymer.dom(this.root).querySelector("dialog-${model.index}");
dialog.open();
}
With this code, dialog is always null, although I can find those dialogs, correctly id-ied, in the DOM tree.
You need to use Polymers DOM API with shady DOM (default). If you enable shadow DOM your code would probably work as well.
PaperDialog infos = new Polymer.dom(this).querySelector("#dialog")

How to remove "on-click" from a custom Polymer component

I have a custom button component done in Polymer Dart:
<div id="buttonDiv">
<my-button id="traceButton"
mode="icon" faicon="fa-comment-o"
toolTip="Print a simple comment"
disabled="false" on-click="{{ traceSomething }}">
</my-button>
</div>
I'm trying to copy/paste this button somewhere else. So a user defines it somwhere, and I basically move it by way of getting $['buttonDiv'].children then inserting it somewhere else. The problem is that {{ traceSomething }} is now irrelevant since it's not part of the new parent. I get errors saying that the parent object, which is another polymer component doesn't have an instance getter "traceSomething".
My question is, is there a way to remove "traceSomething" before I insert it somwhere else? I tried removing the "onClick" event listeners, but the buttons still wants to call that function upon click. Also, I've tried adding a preventDefault, etc, like in: In Dart, if I listen to a click event with two listeners, how do I know which happens first?
But, no luck.
I'm not sure what you mean by copy/past. Do you clone the element, or do you just append it to some other elements children.
Anyway, I don't think you can remove the event listener if it was added declaratively. If you add it imperatively it is easy to remove and readd later.
import 'dart:async';
...
StreamSubscription subsc;
#override
attached() {
super.attached();
subscr = onClick.listen((e) => (this.parentNode as ShadowRoot).host.traceSomething(e));
}
#override
detached() {
super.detached();
if(subscr != null) {
subscr.cancel();
}
}
See also https://stackoverflow.com/a/22168745/217408 about accessing the parent of a Polymer element (for Dart Polymer <= 0.16.x)

Why isn't the keydown event firing?

I'm trying to attach an event handler to the keyDown event in a canvas element. Here is a simplified version of my code.
class CanvasFun{
CanvasElement canvas;
CanvasFun(this.canvas){
print("Game is loading!");
this.canvas.onKeyDown.listen(handleInput);
}
void handleInput(e)
{
//breakpoint is never hit
print(e.keyCode);
}
}
I've removed some of the drawing code. In my main function I simply query the canvas element and pass it to my CanvasFun constructor.
I've also tried doing it this way:
void main() {
var canvas = query("#Game");
canvas.onKeyDown.listen(handleInput);
var canvasFun = new CanvasFun(canvas);
}
void handleInput(e)
{
print(e.keyCode);
}
The reason why the event is not firing is because the focus is on the document (or some other element like an input, for example). And in fact, canvas element even when focused does not fire an event. Some elements do, like input elements.
The solution is to listen to key down events from the document or window:
window.onKeyDown.listen(handleInput);
document.onKeyDown.listen(handleInput); // You already noticed this worked.
John McCutchan has written a nice Dart package to help handle keyboard input. You can read more about it here: http://dartgamedevs.org/blog/2012/12/11/keyboard-input/
Note that this library helps you handle input "correctly". You do not want to do any "work" in the input handling, instead you simply want to register that a key was pressed. You can check the state of any key presses inside of your requestAnimationFrame callback.
Hope that helps!
There exists a workaround to get the canvas-element accept KeyboardEvents:
Problems handling KeyboardEvents on DartFlash
Once you add the tabindex-attribute to your canvas-element, it can get the focus and then it will receive KeyboardEvents.
It looks like I can get it to work if I register the event on the document rather than the canvas element.
document.onKeyDown.listen(handleInput);

Resources