簡體   English   中英

如何在javascriptcore中為Android使用Object.defineProperty

[英]How to use Object.defineProperty in javascriptcore for android

我正在使用該庫在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

還有另一種方式可以做到這一點,雖然它沒有特別有據可查,但卻更為優雅。 您可以使用@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;
    }
}

然后,您可以在Java和Javascript中使用getter / setter方法:

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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM