具有两个视图模型的依赖可观察量?
我正在使用精彩的 Knockout.js 库。我正在使用 javascript 类来捕获结构。例如,几个类之一是:
function OverridableFormItemText(defaultId, defaultText, defaultHelpText, overrideId, overrideText, overrideHelpText)
{
this.DefaultFormItemTextId = ko.observable(defaultId);
this.DefaultText = ko.observable(defaultText);
this.DefaultHelpText = ko.observable(defaultHelpText);
this.OverrideFormItemTextId = ko.observable(overrideId);
this.OverrideText = ko.observable(overrideText);
this.OverrideHelpText = ko.observable(overrideHelpText);
}
如果我在页面中有两个视图模型并且想要添加一个 依赖的可观察对象属性到我的类OverridableFormItemText,那么由于需要将视图模型传递给函数,我是否需要执行两次?
viewModel1.OverridableFormItemText.SomeDependentProperty = ko.dependentObservable(function() {
return this.DefaultText() + " " + this.OverrideText();
}, viewModel1);
viewModel2.OverridableFormItemText.SomeDependentProperty = ko.dependentObservable(function() {
return this.DefaultText() + " " + this.OverrideText();
}, viewModel2);
I am working with the wonderful Knockout.js library. I am using javascript classes to capture the structure. For example, one of several classes is:
function OverridableFormItemText(defaultId, defaultText, defaultHelpText, overrideId, overrideText, overrideHelpText)
{
this.DefaultFormItemTextId = ko.observable(defaultId);
this.DefaultText = ko.observable(defaultText);
this.DefaultHelpText = ko.observable(defaultHelpText);
this.OverrideFormItemTextId = ko.observable(overrideId);
this.OverrideText = ko.observable(overrideText);
this.OverrideHelpText = ko.observable(overrideHelpText);
}
If I have two view models in the page and want to add a dependent observable property to my class OverridableFormItemText, then do I need to do this twice due to the requirement to pass to view model to the function?
viewModel1.OverridableFormItemText.SomeDependentProperty = ko.dependentObservable(function() {
return this.DefaultText() + " " + this.OverrideText();
}, viewModel1);
viewModel2.OverridableFormItemText.SomeDependentProperty = ko.dependentObservable(function() {
return this.DefaultText() + " " + this.OverrideText();
}, viewModel2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,但是您可以使用 DRY 原则使其更易于维护,请查看此示例,其中包含以下视图:
和这段代码:
Yes, but you could make it more maintainable with the DRY principle, have a look at this example with the following view:
And this code:
在这里。发现如果你使用上面的类,你可以在创建依赖属性时引用'this',所以这意味着我不需要为每个视图模型定义依赖属性:
OP here. Found that if you use classes as above, you can refer to 'this' when creating a dependent property, so this means I don't need to define the dependent property for each view model: