我正在开发一个knockout应用程序,其中有一个下拉菜单,用于选择一个月中的某一天,它的值会根据月份选择而变化(例如:May- 1 to 31,Nov- 1 to 30),我成功地渲染了UI,但我的问题是当我尝试从knockout绑定处理程序的更新中更新时,选定的值(this.dayValue
)在UI上没有显示为更新。我已经给出了下面的示例代码,请告诉我。我猜这是重新绑定的问题,尽管我不确定。请帮助。提前感谢。
HTML格式:
<script type="text/html" id="person-template">
<select data-bind="options: months, value: monthValue, event:{change: $data.noOfDays}></select>
**<select data-bind="options: days, value: dayValue, event:{change: $data.dateModifiy}></select>**
<select data-bind="options: years, value: yearValue, event:{change: $data.dateModifiy}></select>
</script>
打字稿:
export class MyView{
private dayValue: Observable<string>;
constructor(opt: Iclass){
this.dayValue = opt.current().getDate().toString();
}
private noOfDays(): void {
let temp: string[] = [];
let month: number = this.months().indexOf(this.monthValue());
let noOfDays: number = new Date(this.yearValue(), month + 1, 0).getDate();
for (let i: number = 1; i <= noOfDays; i++) {
temp.push(i.toString());
}
this.days(temp);
}
}
ko.bindingHandlers.MyDate = {
init(element: HTMLElement, valueAccessor: any, allBindingsAccessor: any, viewModel: any, bindingContext: any): any {
let options: Iclass = ko.utils.unwrapObservable(valueAccessor()) || {};
let myView: Myview = new MyView(options);
ko.cleanNode(element);
ko.applyBindingsToNode(element, {
template: {
name: "person-template",
data: myView
}
});
return { controlsDescendantBindings: true };
},
update(element: HTMLElement, valueAccessor: any, allBindingsAccessor: any, viewModel: any, bindingContext: any): any {
let options: Iclass = ko.utils.unwrapObservable(valueAccessor()) || {};
let myView: Myview = new MyView(options);
}
样品代码:
<div data-bind="MyDate:{ name: 'sample', current: newDate}"></div>
1条答案
按热度按时间aydmsdu91#
你的问题有点不清楚。不过,我猜你是想实现每当选定的月份发生变化时,可选择的日期数组就会更新。
虽然我没有看到具体的问题,但我看到了某种“设计问题”,这可能是问题的根本原因。
在我看来,这样的逻辑应该在viewmodel级别实现(在您的例子中是
MyView
类),因为它与 view 无关,而纯粹与 model 有关。换句话说,要处理可观察数据的变化,您不应该使用change
事件之类的东西通过 view 将其连接起来,而是直接处理可观察数据的通知。我将在
MyView
构造函数中实现类似的内容。通过这种方式,您可以忽略所有的
change
事件,并将状态维护责任传递给 viewmodel。注意,基本上这是所谓MVVM模式的一个关键点。希望这对你有帮助,并解决你的问题。