Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture method missing in Javascript and do some logic?

In Ruby, you can capture a call to a method which is missing and define it on the fly.

What I wanna accomplish in JavaScript is to have an object with no methods. I want a missing method to be translated into a call to emit():

app.isReady() -> app.emit("isReady")
soldier.kills() -> soldier.emit("kills")

I think it's better to capture the missing method error and run emit(methodName) rather than defining all methods (from a fixed list) at runtime. That way we don't have performance overhead if there are hundreds or thousands of events for an object.

What is the best way to do this?

UPDATE: This is an API design so I rather stay out of:

try {
  app.isReady()
} catch(e) {
  ...
}

I want to know how I can accomplish this behind the scenes so the users can use methods as usual.

like image 678
ajsie Avatar asked Feb 22 '23 07:02

ajsie


2 Answers

In that way we don't have a performance overhead if there are hundreds/thousands of events for an object.

I think it's a massive misconception to think the performance overhead of adding methods to an object is smaller then the performance overhead of converting method invocations into emit calls.

However you cannot implement this feature in ES5

One could however implement this using Harmony proxies.

I recommend looking at simulating __noSuchMethod__.

I believe ES6 proxies are experimental and can be turned on in V8 so you could use them with node.js today.

like image 110
Raynos Avatar answered Feb 24 '23 19:02

Raynos


It's not possible to do that consistently at this stage, unless you can guarantee your app will only run on Mozilla, in which case noSuchMethod is what you're after.

As far as I know, none of the other browsers implement this yet.

like image 35
leonardoborges Avatar answered Feb 24 '23 19:02

leonardoborges