From smalltalk to javascript and back

Herbert Vojčík edited this page Jan 29, 2015 · 21 revisions
Clone this wiki locally

Smalltalk ♥ JavaScript

Amber maps one to one with the JavaScript equivalent:

  • String ⇔ String
  • Number ⇔ Number
  • Boolean ⇔ Boolean
  • BlockClosure ⇔ function
  • Error ⇔ Error
  • etc.

JavaScript Objects from Smalltalk

Accessing Existing Objects

You can easily access JavaScript objects directly from Amber and access their properties or call functions:

  1. becomes someUser name
  2. = "John" becomes someUser name: 'John'
  3. console.log('hello world') becomes console log: 'hello world'
  4. window.jQuery('foo').css('background', 'red') becomes (window jQuery: 'foo') css: 'background' color: 'red'

For keyword selectors, only the first keyword matters, all the other keywords will be ignored. That means our previous example could have been: (window jQuery: 'foo') css: 'background' set: 'red'

Note that you can inspect, print, etc javaScript objects from Amber. For example, you can inspect the window object.

Creating Objects

Sometimes you need to create an inline JS object, for example as an argument to this splitter() function:

    splitVertical: true,
    sizeLeft: true

In 99% of these cases, you can simulate the object with a HashedCollection like so:

'#MySplitter' asJQuery splitter: #{
  'splitVertical' -> true.
  'sizeLeft' -> true

Interacting with Smalltalk Objects from JavaScript

Accessing Globals

The globals collection is the entry point for accessing Smalltalk objects.

Inside the loader, globals can be accessed via the argument to the callback. For example

require(['app'], function (amber) {

From anywhere else, use require("amber/helpers").globals.

Sending Messages

Amber also makes it easy to send messages to Smalltalk objects from JavaScript:

  1. Unary messages begin with an underscore: yourself becomes _yourself()
  2. Binary messages are prefixed with 2 underscores: 3@4 becomes (3).__at(4)
  3. Keyword messages follow the same rules as unary messages but with single underscores and a final underscore: aDictionary at: 3 put: 4 becomes aDictionary._at_put_(3, 4)

Instance Variables

A Smalltalk instance variable is accessed from within JavaScript as self['@name'].