2014-06-06 57 views
-1

我有一個包含另一個div的div。內部和外部div具有兩個ViewModel的綁定。內部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')); 
+3

本文介紹瞭如何處理這種情況:http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html –

回答

0

您的要求可以通過使用自定義綁定來完成。你也不需要兩個ViewModels。這只是代碼的重複。

的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'));