2016-09-22 99 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。类似的方法。 –