3

knockout.js の概念を深く掘り下げると、ko.observable にその値を解析/書き込む方法を次のように伝えることができない理由を理解するのに苦労しています。

   dateValue = ko.observable({
        read: function (dateString) {
            /*convert a date string to an object here for internal storage*/
            return Globalize.parseDate(dateString, 'd');
        },
        write: function (dateObj) {
             /*format a date object for output*/
            return Globalize.formatDate(dateObj, 'd');
        }
    })

この目的のために ko.computed が存在することは承知していますが、 read() の結果を書き込む必要がある「シャドウ」オブザーバブルを保持する必要があります。

4

4 に答える 4

6

計算されたオブザーバブルを追加するエクステンダーを作成formattedして、「生の」フォーマットされていない値にアクセスできるようにしながら、フォーマットされた値を読み書きできるようにします。

ko.extenders['date'] = function (target, format) {
    var formatted = ko.computed({
        'read': function () {
            return Globalize.parseDate(target(), format);
        },
        'write': function (date) {
            target(Globalize.format(date, format));
        }
    });
    target.formatted = formatted;
    return target;
};

dateValue = ko.observable('10/19/2012').extend({ 'date': 'd' });

// e.g.,
dateValue();           // 10/19/2012
dateValue.formatted(); // Fri Oct 19 2012 00:00:00 GMT-0700 (Pacific Daylight Time)

dateValue.formatted(new Date(2012, 9, 31));

dateValue();           // 10/31/2012
dateValue.formatted(); // Wed Oct 31 2012 00:00:00 GMT-0700 (Pacific Daylight Time)
于 2012-10-20T02:35:31.037 に答える
0

エクステンダーなしでこのように書くことができます:

// dateValue() is the raw date object
// dateValue.formatted() will return the formatted date as well 
// as parse a date string and save it back to the observable
dateValue = ko.observable();
dateValue.formatted = ko.computed({
    read: function () {
        /*format a date object for output*/
        return Globalize.formatDate(dateValue(), 'd')
    },
    write: function (dateObj) {
        /*convert a date string to an object here for internal storage*/
        dateValue(Globalize.parseDate(dateObj, 'd'));
    }
});
于 2012-10-19T21:21:08.277 に答える
0

いくつかの調査の結果、エクステンダーはまさに私が望むことを行うことがわかりました。たとえば、オブザーバブルの値が設定されるとすぐに自動変換できます。

于 2012-10-19T11:01:54.037 に答える
0

ko.observable の代わりに ko.computed を使用する必要があります。下記参照。通常、オブザーバブルには値またはその他のオブザーバブルのみが含まれます。Computed は、計算を行うことを目的としています

   dateValue = ko.computed({
        read: function () {
            /*convert a date string to an object here for internal storage*/
            return Globalize.parseDate(this, 'd');
        },
        write: function (dateObj) {
             /*format a date object for output*/
            return Globalize.formatDate(dateObj, 'd');
        },
        owner: viewmodel.dateObservable
    })
于 2012-10-19T10:53:51.013 に答える