Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Coerce NodeList into Array to make it iterable #45

Open
Konubinix opened this issue Jul 20, 2020 · 1 comment
Open

Coerce NodeList into Array to make it iterable #45

Konubinix opened this issue Jul 20, 2020 · 1 comment
Labels
enhancement New feature or request

Comments

@Konubinix
Copy link
Contributor

I don't know whether this is the good place to make this request.

Using flexx to create an application, I from time to time need to find all the elements inside a node.
I wish I could write the following for element in self.node.querySelectorAll("a"): .... Unfortunately, this iteration assigns the indexes into element (1, 2, 3...), then I need to write the code as

links = self.node.querySelectorAll("a")
for index in links:
     do something with links[index]

This does not feel very pythonic.

IIUC, the transpiling happens in Parser2._make_iterable, the iteration is converted in

    stub1_seq = this.node.querySelectorAll("a");
    if ((typeof stub1_seq === "object") && (!Array.isArray(stub1_seq))) { stub1_seq = Object.keys(stub1_seq);}
    for (stub2_itr = 0; stub2_itr < stub1_seq.length; stub2_itr += 1) {
      do something with stub1_seq[stub2_itr];
    }

I don't know how NodeList could be taken into account here, I guess that ideally, the condition isArray could be extended to find out other known types that can coerce to Array if(NodeList.prototype.isPrototypeOf(stub1_seq)){stub1_seq = Array.from(stub1_seq);}. I don't know of a more generic way of doing. I python, I would do something like :

try:
    Array.from(stub1_seq)
except ValueError:
    stub1_seq = fallback
@almarklein
Copy link
Member

Good question! The trouble with node-list objects is that they do not behave properly as arrays and their behavior may depend per browser. Auto-converting to an array is an option, but adding a test at every for-loop to check whether the iterate is a nodelist is expensive ... That's why it's as it is now.

I could imagine that a user could explicitly cast it to a list somehow. Maybe just with list()? In PScript we'd then have to do the check when list() is called.

@almarklein almarklein added the enhancement New feature or request label Jul 27, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants