【发布时间】:2015-09-07 16:58:44
【问题描述】:
我的 MVC 5(KnockoutJS 和 TypeScript)应用程序有一个要求,当用户更改选项卡时,我必须使用 ajax 加载一些部分视图。
主页有一个视图模型,稍后当用户更改选项卡时,它应该处理部分视图的绑定。
问题是当我加载部分视图时,绑定似乎不起作用。
这些是我用来加载局部视图并在页面 ViewModel 类中应用绑定的函数:
class ExportViewModel
{
public isBusy: KnockoutObservable<boolean>;
private viewCache: { [key: string]: any } = {};
constructor()
{
this.isBusy = ko.observable(true);
this.getView('someId');
}
private showView(view: any): void
{
var viewContent = $('#view-content');
viewContent.html(view);
ko.applyBindings(this, viewContent[0]);
this.isBusy(false);
}
private getView(someId: string): void
{
this.isBusy(true);
var viewContent = document.getElementById('view-content');
ko.cleanNode(viewContent);
var viewName = someId;
var view = this.viewCache[viewName];
if(view)
this.showView(view);
jQuery.get(`BaseUrl/${viewName}`).done((data: any) =>
{
this.viewCache[viewName] = data;
this.showView(data);
});
}
}
部分视图示例如下:
<div class="panel-body">
@using( Html.BeginForm() )
{
<div class="row">
<div class="col-md-12">
<p>
Sample Partial View
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input data-bind="textInput: isBusy"/>
</div>
</div>
}
</div>
在我的情况下,输入文本是 isBusy 可观察函数的内容,而不是 true 或 false,如果我将输入绑定更改为“textInput: isBusy()”,那么该值为 true这是错误的,因为在 applyBinding 之后我将其设置为 false。
【问题讨论】:
-
能否确认一下是否调用了 showView 方法?还要检查 showView 方法中的“this”指的是什么
-
showView 将被调用,因为如果我删除 applyBinding 则根本不起作用(甚至函数体也不会显示在输入中)。另外我认为“this”应该指的是 vm 类实例而不是函数本身。
-
我们是否缺少某些代码?我没有看到 isBusy = ko.observable();
-
我已经部分地发布了 vm 类。我将更新帖子以包含完整的 VM 类。此外,此行为适用于所有其他 VM 的可观察对象,而不仅仅是 isBusy。
-
您使用的是哪个版本的 knockout.js?
textInput绑定仅在 3.2.0 中添加
标签: c# jquery asp.net-mvc knockout.js typescript