为简单起见,想象一下构建一个流程图设计器。表示每个形状的标记/模板在索引页面上呈现(生成敲除模板的cshtml模板)。用户拖动会删除形状以创建流程图。保存流程图。现在我想重新渲染流程图并将其绑定到已保存的模型数据。一些伪代码
<script name="rectangle" type="text/html">
<input id="rectangle_t" type="text" data-bind="value:rectangle_name"></text>
</script>
<script type="text/javascript">
function RectangleViewModel(){
// instances of this model gets saved when a flowchart containing
// a rectangle is saved
return {
"rectangle_name" : ko.observable()
};
}
</script>
问题: 如何在后端保存后重新呈现流程图?我会从服务器获得一个json和模板,我想重建json的UI表示。流程就像是,构建流程图..构建一个像json数据的树,代表一个流程图,保存,重建流程图。
约束:
提前致谢!
答案 0 :(得分:1)
我认为您正在寻找动态模板,请参阅documentation(注5) 为了重新渲染UI,您只需要使用模板绑定更新您的observable。
<div data-bind='template: { name: shape }' />
和你的javascript代码
function RectangleViewModel(name, shape) {
this.name = ko.observable(name);
this.shape = ko.observable(shape);
this.changeShape = function () {
this.shape(this.shape.peek() === "circle" ? "rectangle" : "circle");
};
};
ko.applyBindings(new RectangleViewModel("Name", "rectangle"));