ko - template 实现两套界面切换

Posted by Sir0xb on 2015-05-19 15:07:09 +0800

准备数据模型

var viewModel= {
    firstName: ko.observable("Planet"),
    lastName : ko.observable("Earth"),
    tempId   : ko.observable("ko-static")
};
 
ko.applyBindings(viewModel);

 

准备锚点和模板

//代码锚点
<div data-bind="template: { name: tempId() }"></div>
 
//展示用模板
<script type="text/html" id="ko-static">
    <table>
        <tr>
            <td>firstName:</td>
            <td data-bind="text: firstName"></td>
        </tr>
        <tr>
            <td>lastName:</td>
            <td data-bind="text: lastName"></td>
        </tr>
    </table>
    <a href="javascript:void(0);" data-bind="click: function(){ this.tempId('ko-edit'); }">Edit</a>
</script> 
 
//编辑用模板
<script type="text/html" id="ko-edit">
    <table>
        <tr>
            <td>firstName:</td>
            <td><input data-bind="value: firstName" /></td>
        </tr>
        <tr>
            <td>lastName:</td>
            <td><input data-bind="value: lastName" /></td>
        </tr>
    </table>
    <a href="javascript:void(0);" data-bind="click: function(){ this.tempId('ko-static'); }">Done</a>
</script>

 

最终效果如下:



Copyright © 2022, Built with Gatsby