knockout.js - KnockoutJS dynamic templates -


please excuse if particular question has been asked. searched through blogs, thread in search of not find particular needs.

i'm trying build single-page application knockout js , i'm relatively new can't seem wrap head around problem.

i have 2 templates:

<script id="template1" type="text/template">    <h3>template 1</h3>    <button id="templbutton" text="go template 2" /> </script> 

and

<script id="template2" type="text/template">    <h3>template 2</h3> </script> 

i have 2 div's bind these templates:

<div data-bind="template: { name: template1 }"></div> <div data-bind="template: { name: template2 }"></div> 

in template 1, have button that, when clicked, should populate template 2 , clear out template 1. there seems no way this, without 3rd party addition?

update 1

on page load, use jquery values first template:

$(document).ready(function(e) {    $.get("/controller/action", function (data) {         // values action, convert array ko function        var results = $.parsejson(data);        var viewmodel = {           somebind = ko.mapping.fromjs(results);        }        ko.applybindings(viewmodel);         // now, thought best way bind button here:        $("#templbutton").click(function(e) {           // , call load of template here,           // however, because have 2 templates on page           // knockout trying bind both.        });    }); }); 

without using 'templatetouse' many posts, threads state, there way this? i'm new all, please excuse if approach seems, stupid.

i've seen threads stating click event should handled knockout:

<button data-bind="click: function(e) { ... }" /> 

but brings me original question, how can load second template, bind when button clicked.

if goal single div, 1 approach do:

<script id="template1" type="text/template">    <h3>template 1</h3>    <button id="templbutton" data-bind="click: swap">go template 2</button> </script>  <script id="template2" type="text/template">    <h3>template 2</h3> </script>  <div data-bind="template: thetemplate"></div> 

with view model like:

ko.applybindings({     thetemplate: ko.observable("template1"),     swap: function() {        this.thetemplate("template2");        } }); 

so, store name of template in observable , update it. sample: http://jsfiddle.net/rniemeyer/sfaph/

if did want in 2 divs, need have flag 1 rendered or visible like:

bind like:

<div data-bind="template: { name: 'template1', 'if': 1 }"></div> <div data-bind="template: { name: 'template2', ifnot: 1 }"></div> 

with view model like:

ko.applybindings({     one: ko.observable(true),     swap: function() {        this.one(false);     } }); 

sample: http://jsfiddle.net/rniemeyer/n2y6z/


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -