blikblum/tinybind

Call custom functions / code

Closed this issue · 2 comments

pwFoo commented

I read about "call functions" (Rivets) and "on-[event]", but could You give me an example how to execute custom code (external included javascript file by script tag)?

pwFoo commented

I think it should / could be done with custom bindings? Have to take a closer look and do some test...

pwFoo commented

@blikblum
Wow! Form example with initial value and a on submit event. Executes an custom (global / external) function.

<!DOCTYPE html>
<html lang="de">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tinybind</title>
    <script src="https://rawgit.com/blikblum/tinybind/master/dist/tinybind.js"></script>
  </head>
  <body>
      <form id="form1" rv-on-submit="submit">
          First name:<br>
          <input type="text" name="firstname" rv-value="firstname"><br>
          Last name:<br>
          <input type="text" name="lastname" rv-value="lastname">
          <input type="submit" value="Submit">
      </form>

      <script>
          function doSubmit(val) {
              console.log(val);
          }

          var model = {
              firstname: "Just",
              lastname: "Me",
              submit(event) {
                  event.preventDefault();   // prevent default action (page reload)
                  var body = new FormData(event.target);    // prepare body as FormData
                  console.log(body);
                  fetch ("http://localhost/form.php", {
                      method: 'post',
                      body: body
                  });
                  // trigger an external / global javascript function outside of tinybind (just as test)
                  doSubmit(model.firstname + " " + model.lastname);
              }
          };
          var view = tinybind.bind(document.getElementById('form1'), model);
          console.log(view);    // debugging
      </script>
  </body>
</html>

I think my question is answered ;)

[EDIT]
Added fetch() example with php $_POST valid body data (FormData).