JavaScript Integration#

Call JavaScript from View#

To integrate with other JavaScript functions, view methods can call an arbitrary JavaScript function after it gets rendered.

<!-- call-javascript.html -->
    function hello(name) {
      alert("Hello, " + name);

  <input type="text" unicorn:model="name" />
  <button type="submit" unicorn:click="hello">Hello!</button>
from django_unicorn.components import UnicornView

class CallJavascriptView(UnicornView):
    name = ""

    def mount(self):"hello", "world")

    def hello(self):"hello",

Trigger Model Update#

Normally when a model element gets changed by a user it will trigger an event which Unicorn listens for (either input or blur depending on if it has a lazy modifier). However, when setting an element with JavaScript those events do not fire. Unicorn.trigger() provides a way to trigger that event from JavaScript manually.

The first argument to trigger is the component name. The second argument is the value for the element’s unicorn:key.

<!-- trigger-model.html -->
  value="initial value"

  document.getElementById("nameId").value = "new value";
  Unicorn.trigger("hello_world", "nameKey");