动态地将视图/模板加载到基因敲除.js中 [英] Dynamically load views / templates in knockout.js
问题描述
我有一张桌子,我想用两种不同的方式显示它.不同数量的列及其内容和单元格的位置. 我想为用户提供一种方法,只需单击一个按钮即可从一个视图切换到另一个视图.
I have a table and I want to show it in two different ways. Different number of columns and position of its content and cells. I would like to provide users with a way to change from one to another view by just clicking a button.
我只是通过使用visible
绑定开始做这件事的,但是后来我意识到这不是正确的方法,因为内容只是invisible
,但它仍然被加载到DOM中.
我在后台复制内容并生成无效的HTML(例如,在两个表中都复制了id
属性),这在jQuery方面产生了问题.
I started doing it by just using the visible
binding, but then I realized it was not the proper way of doing it as the content was just invisible
but it was still being loaded in the DOM.
I was duplicating content in the background and generating invalid HTML (duplicate id
attributes in both tables, for example) and that was generating problems in the jQuery side.
然后,我查看了使用剔除模板来在本例中以 的方式实现,它解决了我以前的问题,并且可以正常工作,但是在<script>
标记内使用HTML听起来对我来说不是最干净的解决方案.
Then I took a look at the use of knockout templates to accomplish it as in this example, and it solves my previous problems and it works, but using HTML inside <script>
tags doesn't sound like the cleanest solution to me.
我不太确定组件的 是否可以提供任何解决方案?在这种情况下,我找不到一个.
I'm not quite sure if the use of components can provide any solution for this cases, I wasn't able to find one.
关于如何处理此问题的任何建议?
Any suggestions about how to deal with this problem?
推荐答案
使用knockout components + AMD
绝对是您想要的.看看knockout
的作者史蒂夫·桑德森(Steve Sanderson)的此.它说明了如何使用ko
和requirejs
构建SPA.它应该清除您的疑问
Using knockout components + AMD
is definitely what you're looking for. Take a look at this by Steve Sanderson, the author of knockout
. It explains how to architect a SPA using ko
with requirejs
. It should clear your doubts
示例:
...
<div data-bind="component: myDynamicComponent"> </div>
...
然后,如果您将组件加载器配置为获取其模板& |或viewModel异步,您可以将myDynamicComponent
作为可观察项:
Then, if you have your component loader configured to fetch its template & | or viewModel asynchronously you can have myDynamicComponent
as an observable:
function RootViewModel(){
var self = this;
this.myDynamicComponent = ko.observable('some-component');
this.someButtonClicked = function() {
self.myDynamicComponent('some-other-component'); // this should render your other component async (only if you configured your component loader to do so)
}
}
这篇关于动态地将视图/模板加载到基因敲除.js中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!