Search code examples
javascriptjsviews

JsViews template for data-linked property editor


There's any way to achieve a "generic" property editor with JsViews? Let's see if I can explain myself: I'd like to have something roughly like this

<script type="text/x-jsrender">
  {{include #data.property1 tmpl="#propeditor" /}}
  {{include #data.property2 tmpl="#propeditor" /}}
  {{include #data.property3 tmpl="#propeditor" /}}
</script>

<script type="text/x-jsrender" id="propeditor">
   <div class="editableField">
     <div>
       <span class="[onClickHideMeAndShowTheDataLinkedInput]">
         {^{>[ref to prop]}}
       </span>
       </div>
         <input type="text" data-link="[prop name] trigger=true" style="display:none;" class="[onBlurShowThePlainTextAgain]" />
       </div>
</script>

In other words, I want to create a somewhat dynamic data linking inside a template, to avoid code replication. Can this be done?


Solution

  • Yes - you can do that. There is a sample on this documentation page: http://www.jsviews.com/#jsvviewobject. Look for Sample: view.childTags().

    It defines a {textbox} tag which you can toggle between editable and non-editable:

    $.views.tags({
      textbox: {
        init: function() {
          var path = this.tagCtx.params.props.path + " trigger=true";
    
          this.template = "<input data-link='~tag.edit' type='checkbox'/> "   // Checkbox to toggle edit
          + "<input data-link='visible{:~tag.edit} {:" + path + ":}'/>"       // <input> for editing
          + "<span data-link='visible{:!~tag.edit} {:" + path + "}'></span>"; // <span> for rendering
        },
        toggleEdit: function() {
          $.observable(this).setProperty("edit", !this.edit);
        }
      }
    });
    

    There is also a variant here https://github.com/BorisMoore/jsviews/issues/134#issuecomment-216694113 which uses switching of templates rather than visibility to toggle editability...