如何在knockout中绑定另一个viewmodel中的viewmodel?

时间:2014-06-06 19:53:19

标签: mvvm knockout.js

我有一个包含另一个div的div。内部和外部div具有两个ViewModel的绑定。内部ViewModel绑定不起作用。我的代码如下:

    <div class='liveExample'>   
        <p>First name: <input data-bind='value: firstName' /></p> 
        <p>Last name: <input data-bind='value: lastName' /></p> 
        <h2>Hello, <span data-bind='text: fullName'> </span>!</h2> 
        <div class='liveExample2'>   
             <p>First name: <input data-bind='value: firstName2' /></p> 
             <p>Last name: <input data-bind='value: lastName2' /></p> 
             <h2>Hello, <span data-bind='text: fullName2'> </span>!</h2>
       </div>
    </div>


// Here's my data model1
var ViewModel = function(first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);

    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();
    }, this);
};

// Here's my data model2
var ViewModel2 = function(first, last) {
    this.firstName2 = ko.observable(first);
    this.lastName2 = ko.observable(last);

    this.fullName2 = ko.computed(function() {
        return this.firstName2() + " " + this.lastName2();
    }, this);
};
 ko.applyBindings(new ViewModel("Planet", "Earth"),document.getElementById('liveExample')); 
ko.applyBindings(new ViewModel2("Planet2", "Earth2"),document.getElementById('liveExample2'));

1 个答案:

答案 0 :(得分:0)

您的要求可以通过使用自定义绑定来完成。此外,您不需要两个ViewModel。这只是代码的重复。

jsFiddle here

<div id='liveExample'>   
        <p>First name: <input data-bind='value: firstName' /></p> 
        <p>Last name: <input data-bind='value: lastName' /></p> 
        <h2>Hello, <span data-bind='text: fullName'> </span>!</h2> 
        <div data-bind="stopBinding: true">   
            <div id='liveExample2'>
             <p>First name: <input data-bind='value: firstName' /></p> 
             <p>Last name: <input data-bind='value: lastName' /></p> 
             <h2>Hello, <span data-bind='text: fullName'> </span>!</h2>
                </div>
       </div>
    </div>



ko.bindingHandlers.stopBinding = {
    init: function() {
        return { controlsDescendantBindings: true };
    }
   };

    // Here's my data model1
    var ViewModel = function(first, last) {
        this.firstName = ko.observable(first);
        this.lastName = ko.observable(last);

        this.fullName = ko.computed(function() {
            return this.firstName() + " " + this.lastName();
        }, this);
    };

   ko.applyBindings(new ViewModel("Planet","Earth"),document.getElementById('liveExample')); 
   ko.applyBindings(new ViewModel("Planet2","Earth2"),document.getElementById('liveExample2'));
相关问题