更新刷新函数中的挖空可观察字符串

Update Knockout Observable string in refresh function

本文关键字:观察 字符串 刷新 函数 更新      更新时间:2023-09-26
代码

在打字稿中,我正在尝试在页面加载时显示当前日期时间并在刷新单击时更新该日期时间。

在显示日期时间的 .ts 文件字符串中,声明方式如下。

   asOfString: KnockoutObservable<string>;

在构造函数中,它是这样设置的,

 this.asOfString = ko.observable(new Date().toDateString() + " " + new Date().toLocaleTimeString());

在 html 中,它是像这样绑定的,

           <a class="small button" data-bind="click: updateSummary">Refresh</a>

在刷新按钮中,我正在尝试像这样更新它,

 this.asOfString(new Date().toDateString() + " " + new Date().toLocaleTimeString()); //latest date time.

它给了我一个错误,_this.asOfString不是一个函数。

请帮忙。

视图模型的代码是这样的,

import ko = require('knockout');
class TodayViewModel {
    asOfString: KnockoutObservable<string>;
    constructor() {
        this.updateSummary();
        this.asOfString = ko.observable(new Date().toDateString() + " " + new Date().toLocaleTimeString());
    }
    updateSummary = () => { // is the function that is bound to refresh button
        //want to update this.asOfString here
    }
}
export = TodayViewModel;  

作为整个应用程序,这对我来说效果很好。我无法说出我正在做的事情与您描述的不同,所以我只是包括整个事情。

class TodayVM {
    asOfString: KnockoutObservable<string>;
    constructor() {
        this.asOfString = ko.observable('');
        this.updateSummary();
    }
    updateSummary = () => {
        this.asOfString(new Date().toDateString() + " " + new Date().toLocaleTimeString())
    }
}
window.onload = () => {
    ko.applyBindings(new TodayVM());
};

.HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>TypeScript HTML App</title>
    <link rel="stylesheet" href="app.css" type="text/css" />
    <script src="app.js"></script>
</head>
<body>
    <h1>TypeScript HTML App</h1>
    <div data-bind="text:asOfString"></div>
    <button data-bind="click:updateSummary">Update</button>
</body>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
</html>