简体   繁体   中英

MustacheJS doesn't render values of functions calling other functions

I have a simple MustacheJS template:

<script id="myTpl" type="text/template">
  <div id="metrics">
    <div>
      <p>Votes: {{ votes.total }}</p>
      <p>Men: {{ votes.men }}</p>
      <p>Women: {{ votes.women }}</p>
      <p>Unknowns: {{ votes.unknown }}</p>
    </div>
  </div>

</script>

<div id="container">
</div>

And there is a JavaScript code:

var data = {
  votes: {
    total: function() {
      return this.voters.men.length + this.voters.women.length + this.voters.unknown.length;
      //return this.votes.men() + this.votes.women() + this.votes.unknown();
    },
    men: function() {
      return this.voters.men.length;
    },
    women: function() {
      return this.voters.women.length;
    },
    unknown: function() {
      return this.voters.unknown.length;
    }
  },
  voters: {
    men: [
      "hpiotrekh",
      "goferek",
      "Carlos_Irwin_Estevez",
      "Nemezis_"
    ],
    women: [],
    unknown: [
      "komurczak",
      "PLDami"
    ]
  }
}

var template = $('#myTpl').html();
var html = Mustache.to_html(template, data);
$('#container').html(html);

In the case when second return statement in votes.total function is commented and we use the first return of that function everything works. But when I try to use the second return statement that uses functions of the object it belongs to, the code doesn't render.

I can't understand why.

Live demo https://jsfiddle.net/bxgnd7ch/

Just comment 4th line and uncomment 5th.

This error caused by function context changed, the actually problem is that you are calling object function by caller this.votes

In total() function

this.voters.men.length + this.voters.women.length + this.voters.unknown.length;

the context this is pointing to data

The problem is :

return this.votes.men() + this.votes.women() + this.votes.unknown()

you invoked this.votes.men() by caller this.votes ,the context this is pointing to data.votes so the context in men/women/unknown function

this === data.votes

Thats why the when the men() function trying to access

this.voters.men.length

its actually accessing data.votes.voters.men.length

but you expected to access data.voters.men.length

so this cause the error.

Solution:

Try to extract the voters out of data object, if you really have to call object function inside of object function

it will be like this: https://jsfiddle.net/bxgnd7ch/3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM