2016-03-31 125 views
0

我想顯示當前日期。我已經寫了下面的代碼,但它並沒有顯示value變量的值。在流星中顯示當前日期

<head> 
    <title>my_first_app</title> 
</head> 

<body> 
    <h1>Hello from Pakistan</h1> 

    {{> hello}} 
    {{> date}} 
</body> 

<template name="hello"> 
    <button>Click Me</button> 
    <p>You've pressed the button {{counter}} times.</p> 
</template> 

<template name="date"> 
    <p>The time now is {{value}}.</p> 
</template> 

JS:

if (Meteor.isClient) { 
    // counter starts at 0 
    Session.setDefault('counter', 0); 

    Template.hello.helpers({ 
    counter: function() { 
     return Session.get('counter'); 
    } 

    }); 

    Template.hello.events({ 
    'click button': function() { 
     // increment the counter when button is clicked 
     Session.set('counter', Session.get('counter') + 1); 
    } 
    }); 

    var value = new Date(); 
    Template.date.helpers(value); 


} 

if (Meteor.isServer) { 
    Meteor.startup(function() { 
    // code to run on server at startup 
    }); 
} 
+2

你必須提供一個對象到'helpers'功能...'Template.date.helpers({值:值} )'甚至是'Template.date.helpers({value})'在ES6中。 –

回答

1

template.date.helpers需要對象,以及每個可退回結果的方法。完全如您對您好模板上的櫃檯幫手所做的那樣:

Template.date.helpers({ 
value: function() { 
    return new Date(); 
} 

});

+0

這會返回初始值,對不對?時間不會動態變化.. – webdeb

+0

每當助手運行時它都會返回一個新的日期對象。你可以將它串起來或者使用一些javascript參數來設置它的格式。這隻會觸發一次,因爲它不是一個被動變量。 –

1

如果你想顯示當前的時間,你可以寫類似下面

Template.date.helpers({ 
    value: function() { 
    return Session.get('currentDate'); 
    } 
}) 

Template.date.onRendered(function(){ 
    // this will update date every second, if you want update for every minute do 60 * 1000 
    Meteor.setInterval(function() { 
    Session.set(currentDate, new Date()); 
    }, 1 * 1000); 

})