gpt4 book ai didi

asp.net - 多个独立 View 模型交互( knockout )

转载 作者:行者123 更新时间:2023-12-03 10:23:30 25 4
gpt4 key购买 nike

我现在在 ASP.Net 应用程序中设置了一个 View 模型来处理一些数据绑定(bind),它与我的主视图上的 Razor 模板交互,该模板在多个页面之间共享。我在 Razor 模板中有一个选择框,它在我当前的 View 模型上有一个数据绑定(bind),但是我必须在多个 View 模型中复制这段代码才能获得相同的功能,我只想让我的 View 模型的这一部分成为就像我的模板一样抽象是它所在的 View 部分的抽象。理想情况下,我想要的是以下内容(伪代码):

class ViewModel1{
function doSomeAjaxStuff(option from select){

}

function doSomethingOnSelectorChange(option from select){
call doSomeAjaxStuff(option from select);

}
}

class SelectorViewModel{
function getSelectorValuesFromAjax(){
//this function will populate the selectors values from an ajax call
}

function sendMessageThatSelectorHasChanged(){
//this will send to the first viewmodel that the selector value has changed

}
}

我对 MVVM 架构有点陌生,我不确定如何通过 knockout 来做到这一点。有人可以帮我吗?

最佳答案

我不确定这是否是您要问的,但听起来您正在寻找使用 Knockout 实现可重用控件之类的东西。我们目前采用的一种方法是将自定义绑定(bind)处理程序与模板脚本结合使用。例如,给定一些模板:

<script type="text/html" id="selector-template">
<!-- ko if: isLoading -->
Loading data...
<!-- /ko -->
<!-- ko ifnot: isLoading -->
<ul data-bind="foreach: items">
<li data-bind="
css: { selected: $parent.selectedItem == $data },
template: $parent.itemTemplate,
click: selectItem">
</li>
</ul>
<!-- /ko -->
</script>

...和一个绑定(bind)处理程序:
ko.bindingHandlers.selector = {
init: function(element, valuesAccessor, allBindingsAccessor, viewModel, bindingContext) {
var bindingValues = valuesAccessor();

var templateElem = document.createElement('div');
templateElem.setAttribute('data-bind', 'template: "selector-template"');
element.appendChild(templateElem);

var viewModelForControl = new SelectorViewModel(bindingValues);
var childBindingContext = bindingContext.createChildContext(viewModelForControl);
ko.applyBindingsToDescendants(childBindingContext, element);
return { controlsDescendantBindings: true };
}
};

...您可以像这样实例化自定义控件:
<div data-bind="selector: { 
itemsUrl: urlForItems,
selected: doSomethingOnSelectorChange,
itemTemplate: 'product-list-item-template'
}"></div>

<script type="text/html" id="product-list-item-template">
<img data-bind="attr: { src: imageUrl }" />
<span data-bind="text: description"></span>
</script>

关于asp.net - 多个独立 View 模型交互( knockout ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17053153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com