Search code examples
javascriptmeteoriron-router

Cant read properties of Object in meteor 's iron router's route


I want to pass object in data context in route. I am trying to read JavaScript object(which holds the business logic) . If i send the object as such , then i can read it's properties in template. But if i try to send a custom object by reading some of it's properties . Then I am getting error that it can not read properties of same object.

this.route('updateBook/' ,
        {
        path:'/updateBook',
    loadingTemplate: 'loading',
    data : function(){
                var Book = Books.findOne({hasFinished:true});

  var UpdateBookObject ={};
    UpdateBookObject.currentPage = Book.currentPage;
    UpdateBookObject.name = Book.name;  
    UpdateBookObject.author = Book.author;
    UpdateBookObject.img = Book.img;
    UpdateBookObject.numOfPages = Book.numOfPages;
    UpdateBookObject.dateStarted = Book.dateStarted;
    UpdateBookObject.dateToFinish = Book.dateToFinish;
    UpdateBookObject.percentage = (UpdateBookObject.currentPage/UpdateBookObject.numOfPages).toFixed(2);
    UpdateBookObject.pagesRemaining = UpdateBookObject.numOfPages - UpdateBookObject.currentPage;
    var finishMoment = moment(UpdateBookObject.dateToFinish,"DD-MM-YYYY");
    var startMoment = moment(UpdateBookObject.dateStarted,"DD-MM-YYYY");
  UpdateBookObject.perDayToRead = finishMoment.diff(startMoment,'days');
  return UpdateBookObject;                      
            }


        });

Solution

  • Pretty sure it's because UpdateBookObject is returning before all of those properties are added to it. Why don't you return the Book variable you declared (which you said works) and then use a template helper to make the calculations?

    Templates.updateBook.helpers({
      updatedBook: function() {
        //return data here
       }
    });
    

    And register global template helpers to do your date parsing for you using moment, this is how I do it for timestamps:

    Global Template Helper:

    Template.registerHelper("dateAndTime", function(date) {
      if(date)
        return moment(date).format('l LT');
    }); //returns formatted Date and Localized Time, e.g. 2/22/2015 12:30PM.
    

    Spacebars in Template:

    {{dateAndTime dateStarted}} //where createdAt is the field in the document
    

    You can also use global template helpers instead of standard ones to do percentage calculations, and just pass the arguments from the Book object in with the Spacebars syntax in your templates.