janl / mustache.js

Minimal templating with {{mustaches}} in JavaScript
https://mustache.github.io
MIT License
16.41k stars 2.39k forks source link

Getting length of Array returned by function #692

Open MikeWarren2014 opened 5 years ago

MikeWarren2014 commented 5 years ago

Suppose I have IIFE (or just plain Object for that matter), defined thusly:

let data = (function() { 
  let _somePrivateDummyData = [
    {
      id : 1,
      name : 'bobbert',
      toString : () => `My name is ${this.name}`
    },
    {
      id : 2,
      name : 'tommy',
      toString : () => `My name is ${this.name}`
    }
  ]

  _somePrivateDummyData.forEach((obj) => obj.toString.bind(obj))

  /* a whole bunch of business logic irrelevant to this MVCE */

  return {
    getSelectedData : () => _somePrivateDummyData.slice()
    /* a smorgasboard of other exposed methods, irrelevant to this MVCE */
  }

})()

I wish to get the length of the selected data, to pass to the view.

Doing {{#getSelectedData}}{{length}}{{/getSelectedData}} doesn't work.

This CodePen shows everything that I have tried, including that.

Failing that, and failing to find relevant documentation on this particular use case, how can we access the length property of an Array the user inputs? I'm trying to decouple the data-handling logic from the view-handling logic as much as possible.

MikeWarren2014 commented 5 years ago

/ apparently CodePen link forgot to post /

phillipj commented 5 years ago

Hi @MikeWarren2014,

sorry for the late reply to this great question!

Do you have to use functions in the data you pass to the view? I did a quick test without a function and it seemed to do the trick:

return {
  getSelectedData : _somePrivateDummyData.slice()
}

Long story short, this looks like it has to do with the JavaScript prototype of the fields in the view.