简体   繁体   中英

How to define a custom property on a dojo gfx shape in a safe way?

I have created a shape object through the surface. Now I wish to associate some custom state with it. I can do it in the most straightforward way:

var rect = surface.createRect(...);
rect.myCustomData = ...;

and hope that no part of dojo or gfx has any logic expecting exactly the same property name.

Is there a way in dojo to safely define custom data on objects produced by it?

PS

I could define a property bag using GUID as the propety name. But it is ugly, no?

There's no way of making sure another part of the JavaScript is relying on that property or not. You could always attempt to validate if it exists before overwriting, for example:

var rect = surface.createRect({
    // Properties
});
if (rect.myCustomData === undefined) {
    rect.myCustomData = myValue;
}

But then you're still not 100% sure, maybe some part of the application relies on the property to be non existing. Even if that's not the case, your property can still be overridden.


Another way is to provide a seperate "map" containing your custom data, for example by having something like:

var rect = surface.createRect({
    // Properties
});

var myCustomData = [ ];
myCustomData.push({
    shape: rect,
    data: myValue
});

To retrieve the data you will have to loop through the map, looking if the shape property matches your shape and then retrieve the data inside the data property.

Then you're sure that no other framework will rely on it, but it means that you have to maintain two seperate parts when creating, updating or deleting shapes.

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