代码之家  ›  专栏  ›  技术社区  ›  Chris Barry

如何使用对象。android javascriptcore中的defineProperty

  •  0
  • Chris Barry  · 技术社区  · 7 年前

    我正在使用这个库在android上运行一些javascript- https://github.com/LiquidPlayer/LiquidCore/wiki/LiquidCore-as-a-Native-Javascript-Engine

    我有一些对象可以毫无问题地向javascript公开,但我想将一些函数作为真正的getter/setter属性绑定到该类。

    在javascript中执行此操作的语法为:

    Object.defineProperty(viewWrapper, 'width', {
        get: function () {
           return viewWrapper.view.width();
        }
    });
    

    http://ericwlange.github.io/org/liquidplayer/webkit/javascriptcore/JSObjectPropertiesMap.html

    我在苹果文档中看到过这样的引用: https://developer.apple.com/documentation/javascriptcore/jsvalue/1451542-defineproperty

    我这样做的原因是为了完美地对现有对象进行阴影处理,因此我必须能够复制getter/setter样式。我可以在javascript层做这项工作,但我正在尝试编写尽可能少的代码,并从java端公开完全格式的对象。

    https://github.com/ericwlange/AndroidJSCore/issues/20

    1 回复  |  直到 7 年前
        1
  •  1
  •   Eric Lange    7 年前

    @jsexport JSObject .

    private class Foo extends JSObject {
        Foo(JSContext ctx) { super(ctx); }
    
        @jsexport(type = Integer.class)
        Property<Integer> x;
    
        @jsexport(type = String.class)
        Property<String>  y;
    
        @jsexport(attributes = JSPropertyAttributeReadOnly)
        Property<String> read_only;
    
        @SuppressWarnings("unused")
        @jsexport(attributes = JSPropertyAttributeReadOnly | JSPropertyAttributeDontDelete)
        int incr(int x) {
            return x+1;
        }
    }
    

    Foo foo = new Foo(ctx);
    ctx.property("foo", foo);
    ctx.evaluateScript("foo.x = 5; foo.y = 'test';");
    assertEquals((Integer)5, foo.x.get());
    assertEquals("test", foo.y.get());
    foo.x.set(6);
    foo.y.set("test2");
    assertEquals(6, foo.property("x").toNumber().intValue());
    assertEquals("test2", foo.property("y").toString());
    assertEquals(6, ctx.evaluateScript("foo.x").toNumber().intValue());
    assertEquals("test2", 
        ctx.evaluateScript("foo.y").toString());
    ctx.evaluateScript("foo.x = 11");
    assertEquals((Integer)11, foo.x.get());
    assertEquals(21, 
        ctx.evaluateScript("foo.incr(20)").toNumber().intValue());
    
    foo.read_only.set("Ok!");
    assertEquals("Ok!", foo.read_only.get());
    foo.read_only.set("Not Ok!");
    assertEquals("Ok!", foo.read_only.get());
    ctx.evaluateScript("foo.read_only = 'boo';");
    assertEquals("Ok!", foo.read_only.get());