简体   繁体   中英

how to bind SVG elements to data?

I'm looking for feedback on my coding technique for designing an interface with Javascript/SVG. I am new to these languages, as I have recently abandoned my specialization in Adobe Flex.

The software will be a generic interface to map source signals to destination signals. Connections are represented by a grid, with rows/columns representing source/destination signals:

X X X X | destination A
X O X X | destination B
X X X X | destination C
X X X X | destination D
---------
1 2 3 4

In this -beautiful- diagram, the "0" represents source 'signal 2' is mapped to 'destination B'.

I am concerned with binding the data (connection objects) to the view (SVG elements). Here's how I did it:

the data is stored in a 2D array: connections[nSources][mDestinations]

In the view, for each item in the 2D array of connections, I create an SVG element with its ID as "celln,m" ("n,m" corresponds to its row/col indices) and add it to the DOM. I found this to be a very simple way to access any SVG element, by using document.getElementById(…), or to find the row/col a user clicked on by parsing the 'evt.target.id' string.

First implementation works well. But I am concerned because the interface needs to support dealing with dynamic data... sources/destination signals will be added or removed on the fly. Rows and columns can be re-arranged by the user. And it will need to support grouping signals into expandable and collapsable nodes.

A simple example: if a new row is added at index 0, I would need to update the IDs of every SVG element to increase its row by 1.

My specific question: is it ok (good practice, safe, and reliable) to be manipulating the IDs of DOM elements this much??

To see a sample of code (the functions that manipulate the IDs of the SVG elements), please see here: sample

It just seems scary that in a grid of 200x200 (for example), adding a row at index 0 means changing the IDs of 40,000 SVG elements. Does anyone see a problem with that?

Anyway, you will use DOM manipulations to achieve your goals. Suggestion: use MVC pattern. Whenever user adds/deletes row, or rearrange them you modify not DOM, but the model. Then you call some listener/callback that redraws SVG. Personally I would detach the whole table (I would keep all rows in one parent <g> , for example) from DOM (with remove operation, or smth like it. What library do you use?). Then, I'll recreate it in memory, and only after that I'll attach ( appendChild to that group) it back. This approach seems to be simple and fast enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM