开发者

Why is the template not getting rendered?

I am wondering why the li is not getting appended.

<! DOCTYPE html>
<html>
<head>
    <title>Trying out knockout</title>
    <script type="text/javascript" src="jquery-1.4.4.js"></script>
    <script type="text/javascript" src="jquery.tmpl.js"></script>
    <script type="text/javascript" src="knockout-1.1.2.debug.js"></script>      
    <script type="text/javascript">
        var viewModel ={
            personName:ko.observable('Stan Marsh'),         
            personAge:ko.observable(28),
            grades:[
                    {subject:"Math",grade:'A'},
                    {subject:"Physics",grade:'B'},
                    {subject:"Chemistry",grade:'A'},
                    {subject:"Biology",grade:'A'}
            ]           
        };      


    $(document).ready(function (){      
        // Apply knockout bindings
        ko.applyBindings(viewModel);
        // Apply templates          
        function renderList() {
          $("#tmplGrades").tmpl(viewModel.grades).append("#ulGradeList"); 
        };      
        // Event Wireup
        $('#btnViewChanges').click(function(){
        var message = "New Name:"+viewModel.personName()+" and New Age:"+ viewModel.personAge();
            alert(message);

        });

    });

    </script>
    <script id="tmplGrades" type="text/html">
    {{each viewModel.grades}}<li>Subject: ${subject} , Grade: ${grade}</li>
    </script>   
</head>
<body>
    <fieldset>
        <legend>Person</legend>
        <p>
            <label for="tbPersonName">Name:</label>
            <input type="text" id="tbPersonName" data-bind="value:pe开发者_开发问答rsonName" />
        </p>
        <p>
            <label for="tbAge">Age:</label>
            <input type="text" id="tbAge" data-bind="value:personAge" />
        </p>
        <input type="button" id="btnViewChanges" value="View Changes"/>
    </fieldset>
    <ul id="ulGradeList">

    </ul>
</body>
</html>


$("#tmplGrades").tmpl(viewModel.grades).append("#ulGradeList"); 

I think you mean appendTo not append.

append appends content to the element selected, while appendTo appends the content selected to the element designated in the selector.


Here is a sample that works: http://jsfiddle.net/rniemeyer/ztgfG/

It looks like in your code the template rendering was in a function called renderList() that was not being called. Additionally, if you pass an array to the template rendering, it will automatically do it for each item in the array, so you did not need to use {{each}}.

The sample on JSFiddle also shows how you can have knockout render the template for you using the template binding. That way you do not have to make the .tmpl call at all.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜