【发布时间】:2017-11-18 14:38:51
【问题描述】:
这里的总新手问题,试图指向正确的方向。
在 HTML 模板中,我有一个 DOM 元素:
<a href=# data-bind="click: $parent.test">«</a>
在 Typescript 文件中,我有:
public test() {
alert("hello");
}
为了让警报功能通过点击被调用,我应该注意什么?
详细说明并添加更多上下文:
我的 ViewModel 如下所示:
import * as ko from 'knockout';
import styles from './QuestCustomBlog.module.scss';
import { IBlogPost, IBlogListings } from './IBlogListings';
export interface IQuestCustomBlogPostBindingContext extends IBlogListings {
shouter: KnockoutSubscribable<{}>;
}
export interface IBlogListings {
BlogPosts: IBlogPost[];
Previous: string; //for paging backwards
Next: string; // for paging forwards
}
export default class BlogListingsViewModel {
public BlogListings: KnockoutObservable<IBlogPost[]> = ko.observable(null);
public Next: KnockoutObservable<string> = ko.observable(null);
public Previous: KnockoutObservable<string> = ko.observable(null);
constructor(bindings: IQuestCustomBlogPostBindingContext) {
this.BlogListings(bindings.BlogPosts);
this.Next(bindings.Next);
this.Previous(bindings.Previous);
bindings.shouter.subscribe((value: IBlogPost[]) => {
this.BlogListings(value);
}, this, 'BlogListings');
bindings.shouter.subscribe((value: string) => {
this.Next(value);
}, this, 'Next');
bindings.shouter.subscribe((value: string) => {
this.Previous(value);
}, this, 'Previous');
}
public test() {
alert('test');
}
}
我的 ko.applybindings 看起来像这样:
export default class QuestCustomBlogWebPart extends
BaseClientSideWebPart<IQuestCustomBlogWebPartProps> {
private _id: number;
private _componentElement1: HTMLElement;
private _koBlogSiteURL: KnockoutObservable<string> = ko.observable('');
private _koBlogListings: KnockoutObservable<IBlogPost[]> =
ko.observable(null);
/**
* Shouter is used to communicate between web part and view model.
*/
private _shouter: KnockoutSubscribable<{}> = new ko.subscribable();
/**
* Initialize the web part.
*/
protected onInit(): Promise<void> {
this._id = _instance++;
const tagName1: string = `BlogListingsComponent-${this._id}`;
this._componentElement1 = this._createComponentElement(tagName1);
ko.components.register(
tagName1,
{
viewModel: BlogListingsViewModel,
template: require('./BlogListingsTemplate.html'),
synchronous: false
}
);
this._getPagedBlogListings()
.then((response) => {
const bindings1: IQuestCustomBlogPostBindingContext = {
BlogPosts: response.BlogPosts,
shouter: this._shouter,
Next: response.Next,
Previous: response.Previous
}
ko.applyBindings(bindings1, this._componentElement1);
})
return super.onInit();
}
您看到的所有绑定都有效,但我似乎无法弄清楚如何将 test() 函数绑定到点击事件...
【问题讨论】:
-
数据绑定非常简单。但是,您的测试函数必须在您的 UI 绑定到的主要对象内。例如,如果您调用了
ko.applyBindings(viewModel),那么 test 必须是“viewModel”中的一个函数 -
谢谢@JasonSpake。我只是在原始问题中添加了更多上下文,希望可以为谜题添加更多内容。
-
我没有看到任何地方都在使用类 BlogListingsViewModel。 Knockout 正在绑定到 IQuestCustomBlogPostBindingContext 的匿名对象,但它没有对您尝试使用的类的任何引用。
-
抱歉,遗漏了一些我认为不相关的细节。刚刚再次更新了原始帖子以提供更多背景信息。
标签: javascript html typescript knockout.js