Sunday, July 15, 2012

Knockout loading views

<!DOCTYPE html">

<html>
    <head>
        <title></title>
        
        <script src="Scripts/jquery-1.7.min.js" type="text/javascript"></script>
        <script src="Scripts/knockout-2.1.0.js" type="text/javascript"></script>

        <script>
            var counter = 0;

            var model1 = function () {
                this.name = ko.observable("model1");
            };

            var model2 = function () {
                this.name = ko.observable("model2");
            };

            var model3 = function () {
                this.name = ko.observable("model3");
            };

            function fetchView(view, model, divDest) {

                var def = new $.Deferred();

                $.ajax({
                    url: "./" + view,
                    success: function (viewContent) {
                        $("<div id=" + divDest + "></div>").appendTo("#container").html(viewContent);
                        def.resolve();
                    }
                });

                def.done(function (pageContent) {
                    counter += 1;
                    $("#counter").html(counter);
                    ko.applyBindings(model, document.getElementById(divDest));
                });
            }

            function init() {
                fetchView("view1.htm", new model1(), "main1");
                fetchView("view2.htm", new model2(), "main2");
                fetchView("view3.htm", new model3(), "main3");
            }
        </script>

        <script>
            $(function () {
                $("#container").html("Main Application");
                $("#counter").html(counter);
                init();
            });
        </script>
    </head>

    <body>
        <div id="counter">
        </div>
        <div id="container">
        </div>
    </body>

</html>

No comments:

Post a Comment