DukeScript: how to access the Java model from the JavaScript context?

477 Views Asked by At

This is related to 1 and 2.

I've read the excellent documentation "Using the Knockout API". That explains how the context is set of a specific widget with knockout bindings.

Now I'd like to be able to access Java models from the Firebug command line, as I would normally do when I access the ViewModel in Javascript using KnockoutJS in a browser. Firebug doesn't know about "$root", basically I don't know how, and whether it'd be possible at all, to access the Java model at all and call @Function methods. That would make for a cool REPL.

2

There are 2 best solutions below

2
On BEST ANSWER

There is the ko.dataFor and ko.contextFor and it might be easier to just use Model = ko.dataFor(document.body);

0
On

Sucess!!!

Here's the trick, I've created a custom binding. In the custom binding init() method, the viewModel is passed. Then I just save the Model into a JavaScript variable.

Step 1: Custom Binding definition

  @net.java.html.js.JavaScriptBody(
      args = {},  body = 
        "ko.bindingHandlers.Model = {" +
            "init: function( element, valueAccessor, allBindingsAccessor, viewModel ){" +
            "Model = viewModel;" +
            "}" +
        "};"
  )
  public static native void registerModel();

Step 2: declare a div in the page with this data-bind:

<div data-bind="Model"></div>

Step 3: register the custom binding in main,onPageLoad():

    MyResource.registerModel();
    MyResource.loadFirebug();
    d.applyBindings();

Step 4: access your model observables and methods from the Firebug console (Model....)

Perhaps there's a more elegant way to data-bind the Firebug div directly, but I haven't managed, perhaps because since Firebug is loaded asynchronously, after applyBindings() is called.

enter image description here