2016-09-22 161 views
0

我有一個用於查詢產品的視圖模型,與此類似。查詢模板查看模型

function ProductQueryModel() { 
    this.publishedSince = ko.observable(); 
    this.nameContains = ko.observable(); 
    ... 
    this.SubmitQuery = function() { 
    // what shall I do? ... 
    } 
} 

現在我創建一個template這個視圖模型,讓我可以重新使用在應用程序。

<template id="productquerymodel-template"> 
    <form> 
    ... 
    <input type="text" data-bind="textInput: nameContains"/> 
    ... 
    <button type="submit" data-bind="click: SubmitQuery">Submit</button> 
    </form> 
</template> 

我故意沒有使用submit結合,因爲在大多數情況下,我想只在點擊按鈕FRM提交防止例如意外提交。

在這裏,我提交表單時出現問題。綁定到提交按鈕的click事件的方法在查詢模型內部沒有意義,因爲查詢模型本身不知道如何處理查詢。它應該是以外的查詢視圖模型,因爲方法實現取決於使用查詢模型的確切內容。

但另一方面,在模板中包含提交按鈕是有意義的,因爲它是表單的一部分。

一個方法是定義clicktemplate$parent.SubmitQuery.bind($parent)內結合,但我會限制模板的消費者總是在查詢模型的父母,這是不是一個很好的定義SubmitQuery功能我認爲解決方案。

有沒有人知道這樣的scnearios現有的做法,或任何其他想法可能有助於在這些情況下?

+0

就像一個更新,還有另外一個替代的解決方案,以這些類型的問題,使用發佈/訂閱模式,例如'knockout-postbox'庫。 –

回答

1

以下是我將如何實現這一目標。

模板文件:

<script type="text/html" id="productquerymodel-template"> 
    <form> 
    <input type="text" data-bind="textInput: nameContains"/> 
    <button type="submit" data-bind="click: SubmitQuery">Submit</button> 
    </form> 
</script> 

<script> 
    function ProductQueryModel() { 
    var self = this; 
    self.publishedSince = ko.observable(); 
    self.nameContains = ko.observable(); 
    self.SubmitQuery = function() { 
     // Do nothing by default 
    }; 
    } 
</script> 

HTML頁面:

<div data-bind="template: { 
    name: 'productquerymodel-template', 
    data: ProductQuery 
}"></div> 

<script> 
    // This would be your main view model for the page 
    function MainViewModel() { 
    var self = this; 
    self.ProductQuery = new ProductQueryModel() 
    } 

    // Initialize an instance of the view model 
    var vm = new MainViewModel(); 

    // Insert your page specific SubmitQuery function here 
    vm.ProductQuery.SubmitQuery = function() { 
    alert('Page specific stuff'); 
    }; 

    ko.applyBindings(vm); 
</script> 

小提琴鏈接:https://jsfiddle.net/dw1284/fopwgf4a/

+0

謝謝我喜歡它,讓我想起了一下Wpf的命令模式。明天再試。 –

+0

是的,我有一個WPF背景,所以我發現自己通常在其他框架上傾向於KnockoutJS。類似的方法。 –