Reputation: 366
I`d like to write a property browser (like .NET propertygrid) for my javascript objects but as a new javascript developer ,I am not sure what is the best way to manage attributes etc. in javascript.
As a C# developer I could use attributes like
[Category("My Properties")]
[Description("Simple Properties")]
[DisplayName("MyText")]
public string SomeText
{
get { return someText; }
set { someText = value; }
}
so my property browser knows necessary information about the properties of my class. It is also important to know the type of property . For example if the type of property is date, the property browser should show a date picker.
My first idea was using variable names.
this.date_StartDate
this.int_Length
and then property grid could just cut off first part of the name and shows StartDate as a datetime property and Length as an integer property.
Please let me know if there is a better method.
Upvotes: 0
Views: 84
Reputation: 6338
There is no real "best" way, although I'd advise against using variable names to signify types.
If you need to support custom types, color for example, I would take the following approach:
My approach would be to add a type to all objects yourself, as a property:
var date = {
value: "31/01/2015",
type: "date"
};
You could also add a type object, as a sort of enum, so you won't spell your types wrong any time.
var types = {
date: "date",
number: "number"
};
This is not needed as long as you use native JavaScript types, like number, string, date and such.
In my own property browser experiment, I simply use typeof to determine what type an object is. JavaScript only has a few basic types (array, undefined, string, number, boolean and function), however, there's a hidden property that you can use to separate a RegEx or a date from an object.
// this function was taken from https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
function toType(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
typeof /aregex/ === "object" // true
typeof new Date() === "object" // true
toType(/aregex/) === "regexp" // true
toType(new Date()) === "date" // true
For some more inspiration, you can take a look at my experimental property browser, it supports numbers, objects, booleans and functions.
Since I couldn't answer your question precisely, I hope this general information can help you find the answer.
Upvotes: 1