2012-12-14 43 views
1

我創建了一個使用Knockout的master-details ui。主控器上的選定事件處理器綁定給定數據項的詳細信息視圖。一切工作到目前爲止,但我想訪問綁定到詳細信息區域的數據,所以我可以將其發佈到服務器,一旦更新。可以在Knockout中綁定後訪問viewModel嗎?

我是Knockout的新手,所以請告知是否有更好的方法。

//the master binding code 
$.ajax({ 
url: getURL, 
success: function (data) { 
var viewModel = new itemModel(data); 
var scope = document.getElementById("listContainer"); 
ko.cleanNode(scope); 
ko.applyBindings(viewModel, scope); 
} 



//the viewmodel with event hander 
function itemWrapper(item) { 
    this.SolutionSet = ko.observable(item.SolutionSet); 
    this.Insight = ko.observable(item.Insight); 
    this.DateFrom = ko.observable(item.DateFrom); 
    this.DateTo = ko.observable(item.DateTo); 
} 

var itemModel = function (data) { 
    var self = this; 
    var observableData = ko.utils.arrayMap(data, function (item) { 
     return new itemWrapper(item); 
    }); 

    self.items = ko.observableArray(observableData); 
    onItemSelected = function (data) { 
     var scope = document.getElementById("itemEditor"); 
     ko.cleanNode(scope); 
     ko.applyBindings(data, scope); 
    }; 
} 

回答

1

我假設你有一個窗體或是你正在編輯你的細節的東西?

剛在你的視圖模型

var itemModel = function (data) { 
    this.onFormSubmit = function (item) { 
    //call ajax and pass you item 
    } 
} 


<form data-bind="submit: itemModel.onFormSubmit"> 
    fields here like so 
    <input data-bind='value: itemModel.DateFrom , valueUpdate: "afterkeydown"'/> 
</form> 
0

onItemSelected功能也許應該讀self.onItemSelected提交(否則它是一個全局變量掛window)。

您可以使用第二視圖模型技術,或者如布恩所示,只需在第一個視圖模型的作用域內使用該表單,並讓Knockout解析它。

地址:

... 
self.selectedItem = ko.observable(); 
self.onDetailsSubmit = function() { 
    self.selectedItem(null); 
    // anything else you want to do 
}; 
... 

到您的視圖模型,並與選定項目的索引更新(或離開它空隱藏形式)。

<form data-bind="visible: selectedItem()"> 
    <!-- ko with: items()[selectedItem()] --> 
    <input type="text" data-bind="value: SolutionSet" /> 
    <input type="text" data-bind="value: Insight" /> 
    <input type="text" data-bind="value: DateFrom" /> 
    <input type="text" data-bind="value: DateTo" /> 
    <button data-bind="click: $parent.onDetailsSubmit">Submit</button> 
    <!-- /ko --> 
</form> 

我從內存中寫道,希望它能正常工作。

相關問題