我是 TypeScript 的新手,我开始学习如何将 knockout.js 与 TypeScript 结合使用,以及如何使用 knockout.js 创建 View 模型。这只是一个试图理解模块内部基本类的简单示例,并且知道我能够使用 Client
类创建数据绑定(bind),它在 name
中正常工作> 和 lastName
,但我有一个 C# 上下文,所以在 C# 中你可以创建一个类,就像类中的属性一样
例如,在 C# 中,您可以像这样创建一个类,使用类 Activity
创建一个属性
public class Client
{
public string ClientName {get;set;}
public Activity Activity {get;set;}
}
public class Activity
{
public string ActivityName {get;set;}
}
//And call this like c# but with typescript sort of
Client client = new Client();
client.Activity = new Activity();
client.Activity.ActivityName = "Activity name";
所以我想用 typescript 和 knockout 重现类似的东西。所以这就是我正在尝试的,但它不工作 activity
“类”我无法获得它的属性和方法。
module Crm {
export class Client {
name: KnockoutObservable<string>;
lastName: KnockoutObservable<string>;
activity: KnockoutObservable<Activity>;
getName() {
return alert(this.name()); //working correctly on the view
}
//constructor(name:string, lastName:string) {
constructor(){
this.name = ko.observable("");
this.lastName = ko.observable("");
this.activity = ko.observable(new Activity());
}
}
export class Activity {
id: KnockoutObservable<number>;
names: KnockoutObservable<string>;
description: KnockoutObservable<string>;
date: KnockoutObservable<any>;
getActivityName() {
return alert("Actividad: " + this.description()); //not working
}
constructor() {
this.id = ko.observable(0);
this.names = ko.observable("");
this.description = ko.observable("");
this.date = ko.observable("");
}
}
var a = new Client();
console.log(a);
ko.applyBindings(new Client());
}
这是我正在测试的简单 html
<p>First name: <input type="text" data-bind="textInput: name" /> </p>
<p>Last name: <input type="text" data-bind="textInput: lastName" /></p>
<button data-bind="click: getName">Get name</button> <!-- working correctly -->
<hr />
<p>Activity</p>
<input type="text" data-bind="activity().description" /> <!-- not working -->
<button data-bind="click: activity().getActivityName">Try me</button> <!-- this click data-bind it's probably wrong, I'm trying to understand how to call the activity method and parameters -->
<script src="~/Scripts/knockout-3.4.2.js"></script>
<script src="~/Scripts/js/client.js"></script>
客户端正在运行,但 Activity 没有运行。我不知道我是否以错误的方式尝试。
最佳答案
getActivityName
的绑定(bind)上下文是 Client
对象,因此您有错误的 this
对象。
- 当前绑定(bind)模型作为第一个参数传递给点击函数。
可以查看fiddle固定代码:
getActivityName(client: Client) {
return alert("Actividad: " + client.activity().description());
}
- 您还可以通过
with
绑定(bind)更改当前绑定(bind)上下文:
```
<!-- ko with: activity -->
<input type="text" data-bind="description" />
<button data-bind="click: getActivityName">Try me</button>
<!-- /ko -->
```
您可以在 this fiddle 中看到这种方法.
关于javascript - 如何在 knockout.js 中实现带有属性的 TypeScript 类作为类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44103588/