Skip to content
This repository has been archived by the owner on Dec 4, 2023. It is now read-only.

Need a way to pass this context to JS functions implemented in Ruby #105

Closed
cowboyd opened this issue Sep 15, 2011 · 0 comments
Closed

Need a way to pass this context to JS functions implemented in Ruby #105

cowboyd opened this issue Sep 15, 2011 · 0 comments
Assignees
Labels

Comments

@cowboyd
Copy link
Collaborator

cowboyd commented Sep 15, 2011

raised by cowboyd/handlebars.rb#4

suppose we have the following code:

V8::Context.new do |cxt|
  cxt['fn'] = lambda do |*args|
    args
  end
  cxt.eval('fn.call("foo", 1,2)') #=> [1,2]
end

there is no way for the lambda bound to fn to access the value of this in the context of the JavaScript call; in this case, the string "foo". We need a way to be able to do this.

Ways to do this:

(A) Pass it in as the first argument to the proc.

V8::Context.new do |cxt|
  cxt['fn'] = lambda do |this, one, two|
    [this,one, two]
  end
  cxt.eval('fn.call("foo", 1,2)') #=> ["foo",1,2]
end

This would basically break every library that uses TRR, but it is obvious what's happening. When you bind an anonymous Ruby function to a JavaScript function, you always get this as the first argument.

(B) Rebind self in the context of the received object

V8::Context.new do |cxt|
  cxt['fn'] = lambda do |this, one, two|
    [self, one, two]
  end
  cxt.eval('fn.call("foo", 1,2)') #=> ["foo",1,2]
end

This might break less code, although it would still break some. Worse, it will probably do so in strange ways. On the other hand, it is more true to the way JavaScript is --constantly keeping you on your toes about what the context is.

In either case, it should be possible to implement these two different strategies in the different contexts.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

1 participant