2013-03-11 85 views
3

我遇到了將新DOM元素綁定到我的viewmodel的麻煩。該元素處於使用AJAX調用加載的局部視圖中(請參閱下面的customizeQuote函數)。在AJAX調用後將新DOM元素綁定到viewmodel

$(function() { 
var mvcModel = ko.mapping.fromJS(initialData); 

function QuoteViewModel() { 
    var self = this; 

    self.customizeQuote = function (quote) { 
     self.selectedQuote = quote; 

     //remove the disable attribute on all form controls before serializing data 
     $(".step").each(function() { 
      $(this).find('input, select').removeAttr('disabled'); 
     }); 

     //convert form data to an object 
     var formData = $('#etape').toObject(); 

     $.ajax("getSelectedQuote", { 
      data: ko.toJSON({ model: self.selectedQuote, model1: formData }), 

      type: "post", contentType: "application/json", 
      success: function (result) { 

       $("#custom").html(result); 
       $("#etape").formwizard("show", "customize"); 
       ko.applyBindings(self.selectedQuote, $("#covers")); 

      } 
     }); 
    } 
} 

var myViewModel = new QuoteViewModel(); 
var g = ko.mapping.fromJS(myViewModel, mvcModel);  
ko.applyBindings(g); 
}); 

這裏的局部視圖的html:

@model QuoteViewModel 
<table id="covers"> 
<thead> 
    <tr> 
     <th> 
      ProductName 
     </th>    
    </tr> 
</thead> 
<tbody data-bind="foreach: CoverQuotesViewModel"> 
    <tr> 
     <td> 
      <input data-bind="value: ProductName" /> 
     </td>   
    </tr> 
</tbody> 
</table> 

行:

ko.applyBindings(self.selectedQuote, $("#covers")); 

觸發一個錯誤:

"ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node"

我是相當新的淘汰賽,我看不到我做錯了什麼。任何想法 ?

回答

7

$("#covers")雖然不是DOM節點,但它是一個jQuery對象。也許嘗試用這個代替:

ko.applyBindings(self.selectedQuote, $("#covers")[0]); 

[0]將得到jQuery對象中選擇的第一個匹配元素。

+0

對!感謝您指出這一點,它現在正在工作。 – Sam 2013-03-11 09:24:53