javascriptjqueryjquery-templatesjsrenderjsviews

How can I load data from jsrender template and update it


I'm working on migrating Jquery template with JSRender library. I need to retrieve data object from the template page and after that I need to update corresponding property. My old jquery.tmpl code is given below:

JavaScript

function updateItem(event) {
  var $tmplItem = $(this).tmplItem();
  $tmplItem.data.showItem = !$tmplItem.data.showItem;
  $tmplItem.update();
}

html

{{if showItem}}
 <div>
  This is your item.
 </div>
{{else}}
 <div>
  No item.
 </div>
{{/if}}

How can I convert this code into jsRender. I did the following:

JavaScript

function updateItem(event) {
  var $tmplItem = $(this).view().ctx.root[0];
  $tmplItem.showItem = !$tmplItem.showItem;
  //$tmplItem.update();
}

$(this).view() method from JSviews will helps to retrieve the data from the template. But it is not the exact result which I got from $(this).tmplItem(). But there is no update() method. Is there any solution to rebind the updated showItem property to template? I tried some steps from here https://stackoverflow.com/a/9780530/9338568


Solution

  • You can use dynamic data binding provided by JsViews, but to do so you need to load the template with JsViews:

    $.templates("#pageTmpl").link("#page", data, helpers); // Render and link the template
    

    Next, when you modify data values, and you want to trigger updated content binding to the new values, you cannot just write:

    $tmplItem.data.showItem = !$tmplItem.data.showItem;
    

    since that will not raise any event to trigger re-binding. Instead, make an observable change, like this:

    $.observable($tmplItem).setProperty("showItem", !$tmplItem.showItem);
    

    And now for any tags which you want to bind dynamically to data, use the 'data-linked' syntax: {^{...:

    In your sample, {{if showItem}}, will be re-written as:

    {^{if showItem}}
    

    You can see all that illustrated in this sample code, based on your content:

    https://jsfiddle.net/BorisMoore/ctzL3xeg/2/

    (The sample also shows an alternative approach to binding events: <button data-link="{on ~updateItem}">Click me JsV</button>)

    See JsViews QuickStart for more information.