具有两种视图模型的相关可观察量?

时间:2011-09-05 15:55:32

标签: javascript mvvm knockout.js

我正在使用精彩的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中添加dependent observable property,那么是否需要执行此操作两次,因为需要将模型传递给函数吗

viewModel1.OverridableFormItemText.SomeDependentProperty = ko.dependentObservable(function() {
    return this.DefaultText() + " " + this.OverrideText();
}, viewModel1);

viewModel2.OverridableFormItemText.SomeDependentProperty = ko.dependentObservable(function() {
    return this.DefaultText() + " " + this.OverrideText();
}, viewModel2);

2 个答案:

答案 0 :(得分:3)

是的,但您可以使用DRY原则使其更易于维护,请使用以下视图查看此example

<p>First name: <span data-bind="text:  viewModel2.firstName"></span></p>
<p>Last name: <span data-bind="text:  viewModel2.lastName"></span></p>
<h2>Hello, <input data-bind="value:  viewModel2.fullName  "/>!</h2>

<p>First name: <span data-bind="text: viewModel.firstName"></span></p>
<p>Last name: <span data-bind="text:  viewModel.lastName"></span></p>
<h2>Hello, <input data-bind="value:  viewModel.myFullName  "/>!</h2> 

这段代码:

var viewModel = {
    firstName: ko.observable("Planet"),
    lastName: ko.observable("Earth")
};

var viewModel2 = {
    firstName: ko.observable("Exoplanet"),
    lastName: ko.observable("Earth")
};

function FullNameDependentObservable(viewmodel, f, property) {
    viewmodel[property] = ko.dependentObservable(f, viewmodel);
}

var AddNames = function() {
    return this.firstName() + " " + this.lastName();
};

FullNameDependentObservable(viewModel, AddNames, "myFullName");
FullNameDependentObservable(viewModel2, AddNames, "fullName");

ko.applyBindings(viewModel);
ko.applyBindings(viewModel2);

答案 1 :(得分:1)

OP在这里。发现如果你使用上面的类,你可以在创建依赖属性时引用'this',这意味着我不需要为每个视图模型定义依赖属性:

            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); 
                this.SomeDependentProperty = ko.dependentObservable(function() { return ('Dependent' + this.DefaultText() )}, this);
            }