【问题标题】:How to bind a viewmodel in another viewmodel in knockout?如何在淘汰赛中将视图模型绑定到另一个视图模型中?
【发布时间】:2014-07-28 04:29:15
【问题描述】:

我有一个包含另一个 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'));

【问题讨论】:

标签: mvvm knockout.js


【解决方案1】:

您的要求可以通过使用自定义绑定来实现。此外,您在这里不需要两个 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'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 2012-06-17
    • 2021-09-12
    • 2014-09-07
    • 1970-01-01
    相关资源
    最近更新 更多