Subj : Re: problem on setter of object;'s property To : lyg From : Brendan Eich Date : Mon Feb 09 2004 08:32 am lyg wrote: >when i set the value property of a option object , why the GetOptionProperty >function is not called ? > >what is wrong ? Thanks! > >/*declare option object's property GETTER*/ >static JSBool GetOptionProperty (JSContext *cx, JSObject *obj, jsval id, >jsval *vp); > >static JSClass OptionClass = { > "Option",0, > JS_PropertyStub,JS_PropertyStub, JS_PropertyStub, >JS_PropertyStub,JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, >JS_FinalizeStub,JSCLASS_NO_OPTIONAL_MEMBERS >}; > >enum OPTION_PROP_ID { > > OPTION_VALUE = 0, > OPTION_TEXT, >}; > >static JSPropertySpec OptionProperties[] = >{ > {"value", OPTION_VALUE, >JSPROP_ENUMERATE|JSPROP_READONLY, GetOptionProperty}, > {"text", OPTION_TEXT, >JSPROP_ENUMERATE|JSPROP_READONLY, GetOptionProperty}, > {0} >}; > >static JSBool >Option(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) >{ > if (0 < argc && 5 > argc) > > This might be more readable of it used number-line order (0 < argc && argc < 5). Why 5? > { > char *temp; > temp = JS_GetStringBytes( JSVAL_TO_STRING(argv[0]) ); > > JS_SetProperty(cx, obj, "text", &argv[0]); > if (argc > 1) > JS_SetProperty(cx, obj, "value", &argv[1]); > > How is this supposed to work, given that value is readonly? > return JS_TRUE; > } > else return JS_FALSE; > > 1. else after return is a non-sequitur. 2. Never return false without first calling JS_ReportError or JS_SetPendingException, or calling something that does that before it returns false or null. >} > >JSObject * >js_InitOptionClass(JSContext *cx, JSObject *obj) >{ > JSObject *proto; > > proto = JS_InitClass(cx, obj, NULL, &OptionClass, Option, 4, > NULL, NULL, OptionProperties, NULL); > if (!proto) > return NULL; > OBJ_SET_SLOT(cx, proto, JSSLOT_PRIVATE, JSVAL_FALSE); > > Do not use OBJ_SET_SLOT or include jsobj.h! Use only jsapi.h. Why would you set the private slot on an object whose class lacks the JSCLASS_HAS_PRIVATE flag? That's an error, and if you had used the proper API (JS_SetPrivate) and tested a DEBUG-compiled version of this code, you would have hit an assertion telling you so. > return proto; >} > >static JSBool GetOptionProperty (JSContext *cx, JSObject *obj, jsval id, >jsval *vp) >{ > int i = 9; > return JS_TRUE; >} > > Despite the above small and large problems, you have not shown enough to say why the value getter is not being called. But fix the above first, retest, and debug a little -- try breakpointing in js_GetProperty and stepping into functions called from it. /be .