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

倖福魔咒の 提交于 2020-01-25 17:27:22

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/30632856/dukescript-how-to-access-the-java-model-from-the-javascript-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!