[gjs] Lang.js: Add defineAccessorProperty



commit 00b31c76c93251a02d1e3146c16da78c6daa9eca
Author: Giovanni Campagna <gcampagna src gnome org>
Date:   Thu Jun 30 15:06:30 2011 -0400

    Lang.js: Add defineAccessorProperty
    
    This is a wrapper for Object.defineProperty() but with a fallback for
    older versions of spidermonkey.

 modules/lang.js     |   14 ++++++++++++++
 test/js/testLang.js |   15 +++++++++++++++
 2 files changed, 29 insertions(+), 0 deletions(-)
---
diff --git a/modules/lang.js b/modules/lang.js
index 5642a01..061468e 100644
--- a/modules/lang.js
+++ b/modules/lang.js
@@ -114,5 +114,19 @@ function bind(obj, callback) {
     };
 }
 
+function defineAccessorProperty(object, name, getter, setter) {
+    if (Object.defineProperty) { // ECMAScript 5
+	Object.defineProperty(object, name, { get: getter,
+					      set: setter,
+					      configurable: true,
+					      enumerable: true });
+	return;
+    }
+
+    // fallback to deprecated way
+    object.__defineGetter__(name, getter);
+    object.__defineSetter__(name, setter);
+}
+
 // Merge stuff defined in native code
 copyProperties(imports.langNative, this);
diff --git a/test/js/testLang.js b/test/js/testLang.js
index 3ab3474..df2725d 100644
--- a/test/js/testLang.js
+++ b/test/js/testLang.js
@@ -108,4 +108,19 @@ function testBind() {
     assertEquals("o3.args[4] in callback", 1138, o3.args[4]);
 }
 
+function testDefineAccessorProperty() {
+    var obj = {};
+    var storage = 42;
+
+    assertEquals(obj.foo, undefined);
+
+    Lang.defineAccessorProperty(obj, 'foo',
+				function () { return storage; },
+				function (val) { storage = val; });
+
+    assertEquals(obj.foo, 42);
+    obj.foo = 43;
+    assertEquals(obj.foo, 43);
+}
+
 gjstestRun();



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]