manatlan / htag

Python3 GUI toolkit for building "beautiful" applications for mobile, web, and desktop from a single codebase
https://manatlan.github.io/htag/
MIT License
99 stars 4 forks source link

dom manipulation #13

Open rraammiinn opened 12 months ago

rraammiinn commented 12 months ago

what's the proper way of dom manipulation in python side (how to select elements) ?

manatlan commented 12 months ago

how to select elements

you can't ;-) in fact, you should keep the instance of a htag element in a ref ...

example:


# admit you create an element div
mydiv = Tag.div("hello")

# you append mydiv to the current tag instance
self += mydiv

# if you want to change attributs ... it's like that
mydiv["class"]="mycolor"
mydiv["title"]="it's my div"

# if you want to add an event ... it's like that
mydiv["onclick"]= self.mymethod

# if you want to change content... it's like that
mydiv.set("hello world")

# if you want to add nodes... it's like that
mydiv += Tag.span( "a sub element of mydiv " )

# if you want to clear content... it's like that
mydiv.clear()

# if you want to remove the node... it's like that
mydiv.remove()

# and you can iterate on its childrens
# (but here, in context : it has no sense, because you just removed it with the previous statement ;-) )
for i in mydiv.childs:
    ...

alternativly, you could do something like that (but it's a bad practice) :

# you append your div at its init ...
self += Tag.div( "hello" )

# and refer to it, lately
mydiv = self.childs[-1]  # refer to last added tag

it's pretty basic ... but it works well ;-)

rraammiinn commented 12 months ago

how to select elements

you can't ;-) in fact, you should keep the instance of a htag element in a ref ...

example:

# admit you create an element div
mydiv = Tag.div("hello")

# you append mydiv to the current tag instance
self += mydiv

# if you want to change attributs ... it's like that
mydiv["class"]="mycolor"
mydiv["title"]="it's my div"

# if you want to add an event ... it's like that
mydiv["onclick"]= self.mymethod

# if you want to change content... it's like that
mydiv.set("hello world")

# if you want to add nodes... it's like that
mydiv += Tag.span( "a sub element of mydiv " )

# if you want to clear content... it's like that
mydiv.clear()

# if you want to remove the node... it's like that
mydiv.remove()

# and you can iterate on its childrens
# (but here, in context : it has no sense, because you just removed it with the previous statement ;-) )
for i in mydiv.childs:
    ...

alternativly, you could do something like that (but it's a bad practice) :

# you append your div at its init ...
self += Tag.div( "hello" )

# and refer to it, lately
mydiv = self.childs[-1]  # refer to last added tag

it's pretty basic ... but it works well ;-)

thanks .

it worked but there is two problems :

  1. dom manipulation resets elements content .
  2. there isn't an easy way for two way data binding .