2012-12-20 56 views
1

我試圖避免冗餘,並調用通用XTemplate格式化時間戳中的日期和時間。ExtJS XTemplates:從另一個模板調用模板

這不會輸出我期望的字符串,只是UI中的[Object object]。

SCB.RMWB.templates = { 
    timeStamp: function(stamp) { 
     return new Ext.XTemplate( 
      '<span class="time-frame">{[ this.dateRangeMsg(stamp) ]}</span>', 
      { 
       dateRangeMsg: function(stamp) { 

        console.log('stamp', stamp);  

        var dateTime = new Date(), 
         now = Ext.Date.format(dateTime, 'U'),   // gives us seconds since the UNIX Epoch from Ext.Date class 
         offset = Ext.Date.format(dateTime, 'Z'),  // gives us GMT offset from Ext.Date class 
         minutesAgo = (now - 300),      // 5 minutes ago 
         hourAgo = (now - 3600),       // one hour ago 
         msg = ''; 


        if (stamp >= minutesAgo && stamp <= now) { 
         msg = 'Moments ago'; 
        } else if (stamp >= hourAgo && stamp <= now){ 
         msg = '1 hour ago'; 
        } else { 
         msg = this.formatGMT(stamp, offset).toString(); 
        } 

        return msg; 

       }, 
       formatGMT: function(stamp, offset){ 

        var time; 

        // * 1000 gives us date string to format in Ext.Date class 
        if (offset > 0){ 
         time = new Date((stamp - offset) * 1000);  
        } else { 
         time = new Date((stamp + offset) * 1000); 
        } 

        return Ext.Date.format(time, 'd-M-y, H:i \\G\\M\\T'); 

       }     
      } 
     ); 
    }, 
    notifications: { 
     flyout: function(){ 
      return new Ext.XTemplate(
       '<tpl for=".">',  
        '<li id="notification-flyout-{id}">', 
         '<div class="data-details">', 
          '<p>{message}</p>', 
          '{[ this.renderTimeStamp(values.sentDate) ]}', 
         '</div>', 
        '</li>', 
       '</tpl>', 
       { 
        renderTimeStamp: function(stamp) { 
         return SCB.RMWB.templates.timeStamp(stamp); 
        }    
       } 
      ); 
     } 
    } 
}; 

如果我繼續時間戳功能,在原始模板它工作正常,但是這個功能將在不同的模板幾個地方使用,所以我想更多的東西通用的,我可以重新使用。

+1

就分別定義了兩個函數和引用它們作爲你的模板定義方法。或者做'SCB.RMWB.templates.timeStamp.call(this,stamp)' - 你需要有正確的上下文。 – katspaugh

回答

2

嗯,我的代碼示例中有一些難點需要關注,但在您的模板實例上調用apply時,它應該適用於您。

詳細:

創建要一個輔助命名空間內重複使用一次的模板。爲了重用它,提供了一個獲取該實例以及提供的數據的方法。

var tpl = new Ext.Template('Name: {name}, Age: {age}'); 
tpl.apply({name: 'John', age: 25}); // returns a html string 

這裏,(更詳細)JSFiddle

相關問題