无法读取流星中对象的属性's iron路由器's路线

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

本文关键字:iron 路线 路由器 属性 读取 流星 对象      更新时间:2024-07-02

我想在路由中的数据上下文中传递对象。我正在尝试读取JavaScript对象(它包含业务逻辑)。如果我这样发送对象,那么我可以在模板中读取它的属性。但是,如果我试图通过读取自定义对象的一些属性来发送它。然后我得到了一个错误,它不能读取相同对象的属性。

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;                      
            }

        });

很确定这是因为UpdateBookObject在所有这些属性添加到它之前就返回了。为什么不返回您声明的Book变量(您说它有效),然后使用模板助手进行计算呢?

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

注册全局模板助手,使用moment为您进行日期解析,这就是我为时间戳所做的:

全局模板帮助程序

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.

模板中的空格键

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

您也可以使用全局模板辅助对象而不是标准模板辅助对象来进行百分比计算,只需将Book对象中的参数与模板中的空格键语法一起传入即可。