It’s a productive weekend. Surfing around and found Mozilla Rhino as a Javascript interpreter, and took less than a day to integrate and test it with Android-Binding. Well, that ends up to be a plugin library for Android-Binding which is about 600Kb in size, where 590Kb goes to Rhino. It’s a little too big, so I decided that to be plugin, if anyone need this extra power can go for this one.

This plugin actually consists of one Converter only: JS, currently this converter is able to convert TO but not back. Following is the syntax:

JS(scope, js_statement, dynamic_object(optional))

For scope, it is the VM where the script will look for the observables, so in most cases, just passing “.” (self)  in it will be fine; js_statement is simply javascripts wrapped with string literal. the last statement, dynamic_object, is for putting additional arguments.

All the observables, which referenced in the js statements, will auto wired up and whenever changes happen in any observables, the js_statement will be re-evaluated too.

Examples

Assume the view model has a Hello observable with value “yes”

binding:text="JS(., 'Hello;')" => "yes"

The following “"” is not a mistake, it is the escape for xml’s double quote, so that we can use single-quote in javascript

binding:text="JS(.,
  "
    Hello;
  ")" => Same as above, wrapping with " gives more flexibility in writing js codes
binding:text="JS(., " 'Test from JS ' + Hello; ")" => "Test from JS yes"

If not using “"” the above will became…

binding:text="JS(.,' "Test from JS " + Hello; ')" => "Test from JS yes"

You can define function too!

binding:text="JS(.,
  "
    function add(a, b){ return a + b; }
    add('Test from JS ', Hello);
  ")" => "Test from JS yes"

Standard JS libraries can be use too:

binding:text="JS(.,
  "
    Hello.length + Math.sin(0);
  ")" => "6";

Eval (use) Android Binding Syntaxes in js

binding:text="JS(.,
  "
    $('CONCAT(Hello, Hello)');
  ")" => "yesyes"

Most binding syntaxes is fine, except referencing other View attributes

binding:text="JS(.," $(@string/hello); ")" => Value of the @string/hello res.

Placing Extra Arguments (probably referencing other view attributes)

binding:text="JS(.,
  "
    name + age;
  ", { name='adam', age='30' })" => "adam30";

Requirements

Android-Binding v0.49 and up

Advertisements