Search code examples
javascriptjqueryjsrenderjsviews

Helper functions in jsviews


I am going through the following examples in JsViews site for buttons http://www.jsviews.com/#link-button. When I modify the code to take an input and display the same in the alertbox on clicking the button, the helper function gets executed onload. Also, instead of on click of the button, the function gets executed when the input value changes. I am guessing since the model value is changed in the view, the function gets called with the updated model value but why is it not working on click of the button. I am quite new to jsviews and not able to understand what is happening. Can anyone tell me what is wrong with my approach. Below is the updated code.

<div id="topLinked">
<input type="text" data-link="test"/>
 <button data-link="{on ~doSomething(test)}">Do something</button>
<input type="button" data-link="{on ~doSomething(test)}" value="Do something" />
           </div>  

  var person = {};

var helpers = {
  doSomething: function(val) {
    alert(val);
  }
}

$.link(true, "#topLinked", person, helpers); // Data-link top-level content

Solution

  • You made a mistake this: data-link="{on ~doSomething(test)}". Arguments are passed through the one or more spaces like this: data-link="{on ~doSomething test test2 ...}".

    I changed the example like this:

    html

    <div id="result"></div>
    
    <script id="tmpl" type="text/x-jsrender">
      <input type="text" data-link="test" value="Do something" />
      {^{on ~doSomething test}}Do something{{/on}}
      <button data-link="{on ~doSomething test}">Do something</button>
      <input type="button" data-link="{on ~doSomething test}" value="Do something" />
    </script>
    

    js

    var person = {
        test : "start value"
    };
    
    var helpers = {
        doSomething : function (val) {
            alert(val);
            return false;
        }
    }
    
    var tmpl = $.templates("#tmpl");
    tmpl.link("#result", person, helpers);
    

    example on jsfiddle