Skip to content

Commit

Permalink
✅ Find a way to perform JS's asynchronous call from Crystal
Browse files Browse the repository at this point in the history
  • Loading branch information
TheEEs committed Apr 26, 2021
1 parent da9fb4b commit 839ba83
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
19 changes: 18 additions & 1 deletion spec/alizarin_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ describe "JSCClass" do
end

describe WebExtension::Chainable do
it "works" do
it "works" do
eval_js <<-JS
var me = new Person();
me.set_name("TheEEs").greet();
Expand All @@ -126,3 +126,20 @@ describe WebExtension::Chainable do
ret.should eq "Hello TheEEs"
end
end

describe "async" do
it "works" do
eval_js <<-JS
var result = do_it_later(function(result){
window.a = "Hello";
});
JS
script_result
sleep 0.4
eval_js <<-JS
window.a;
JS
ret = String.new JSC.to_string script_result
ret.should eq "Hello"
end
end
19 changes: 16 additions & 3 deletions webExtensions/extension.cr
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ class XAML::MyFileReader < File
end
end

class Person
INSTANCES = [] of Void*
class Person
INSTANCES = [] of Void*
@name = ""

def self.new(params)
Expand All @@ -25,7 +25,7 @@ class Person
@[JSCInstanceMethod]
@[Chainable]
def set_name(p)
@name = p.first.to_s
@name = p.first.to_s
Box.box(self)
end

Expand Down Expand Up @@ -113,6 +113,19 @@ initialize_extension do
}
end)

do_it_later = function p do
sto = JSCContext.get_value("setTimeout").as(JSCFunction)
cb = p.first
o = JSCObject.new
o["c"] = cb
sto.call(
function pp do
o["c"].as(JSCFunction).call
end, 0)
end

JSCContext.set_value "do_it_later", do_it_later

JSCContext.set_value "MyFileReader", register_class(XAML::MyFileReader)
JSCContext.set_value "Person", register_class(Person)
end

0 comments on commit 839ba83

Please sign in to comment.