2014-12-11 3 views
0

날짜 서식을 지정하기 위해이 샘플 코드 (.js 라이브러리를 사용해야합니다.)가 있습니다. 부분 기능을 사용하기 전에 사용법을 확실히 모르기 전에 사용해 본 적이 없습니까? 어떻게 전화하나요?부분 함수를 호출하는 방법

define(function() { 
    'use strict'; 

    function _formatDate(justNowText, todayFormat, thisWeekFormat, thisYearFormat, veryOldFormat, date) { 
     if (!date) { return ""; } 

     var formattedMoment = moment(date); 
     var now = moment(); 

     if (now.diff(formattedMoment, "minutes") < 15) { 
     return justNowText || "Just now"; 
     } 

     var today = now.startOf('day'); 
     var dateFormat; 

     if (today <= formattedMoment) { 
     dateFormat = todayFormat; 
     } else if (now.diff(formattedMoment, "days") < 7) { 
     dateFormat = thisWeekFormat; 
     } else if (formattedMoment.year() >= now.year()) { 
     dateFormat = thisYearFormat; 
     } else { 
     dateFormat = veryOldFormat; 
     } 

     return formattedMoment.format(dateFormat); 

    } 

    function asShortTimeStampFilter(gettext) { 
    return _.partial(_formatDate, 
     gettext("Just now"), 
     "h:mm A", 
     "ddd", 
     "MMM D", 
     "M/D/YY" 
    ); 
    } 

    function asMediumTimeStampFilter(gettext) { 
    return _.partial(_formatDate, 
     gettext("Just now"), 
     "[" + gettext("Today at") + "] h:mm a", 
     "ddd h:mm a",_formatDate 
     "MMM D h:mm a", 
     "M/D/YYYY h:mm a" 
    ); 
    } 

    function asDateTimeFormatFilter(gettext) { 
    return function(date, format) { 
     if (!date) { return; } 

     return moment(date).format(format); 
    }; 
    } 

    return { 
    asShortTimeStamp: ['gettext', asShortTimeStampFilter], 
    asMediumTimeStamp: ['gettext', asMediumTimeStampFilter], 
    asDateTimeFormat: ['gettext', asDateTimeFormatFilter] 
    }; 
}); 

답변

3

Partial application 당신이 다음 최종 인수 (여러 번)를 호출 할 수있는, 다시 함수를 얻을 첫 번째 인수를 전달 것을 의미 다음은 유틸리티 라이브러리 코드입니다.

귀하의 경우 라이브러리는 텍스트 게터 기능 (예 : 현지화 용)을 기대하며 날짜를 전달할 실제 포맷터 기능을 반환합니다.

function id(x) { return x } // just echo the input 
var shortTimeStamp = library.asShortTimeStamp[1](id); 

console.log(shortTimeStamp(Date.now())) 
console.log(shortTimeStamp(Date.now() - 30000)) // 30s ago 
console.log(shortTimeStamp(Date.now() - 720000)) // 2h ago 

var mediumGermanTimeStamp = library.asMediumTimeStamp[1](function(t) { 
    return {"Just now":"Grad vorhin", "Today at":"Heut um"}[t]; 
}); 

console.log(mediumGermanTimeStamp(Date.now())) 
console.log(mediumGermanTimeStamp(Date.now() - 30000)) // 30s ago 
console.log(mediumGermanTimeStamp(Date.now() - 720000)) // 2h ago 
+0

@ bergi..thanks는 답장을 남겼습니다. 죄송합니다. 확실하지 않습니다. – Surily

+0

'id'는 신원 기능입니다. ''Just now ''라는 문자열로 호출되면, 그냥 "기본"지역화라고 말할 것이다. – Bergi

+0

나는 당신의 대구의 마지막 3 줄을 기록하려고 시도했다. 단지 'Grad vorhin'을 매번 반환한다. – Surily