1

我正在尝试用用 Backbone.js 编写的全新界面替换现有的 Web 应用程序。最终,这将是非常棒的,因为该应用程序由一个用 Python + CherryPy 编写的宁静 API 支持,并且讨厌刷新其主机页面。

我的第一步是尝试使用在 'net. 这是我想出的:

<!DOCTYPE html>
<html>
<head>
    <script type="application/javascript" src="/static/js/jquery-1.8.2.min.js"></script>
    <script type="application/javascript" src="/static/js/underscore-min.js"></script>
    <script type="application/javascript" src="/static/js/json.js"></script>
    <script type="application/javascript" src="/static/js/ICanHaz.min.js"></script>
    <script type="application/javascript" src="/static/js/backbone.js-0.9.9-min.js"></script>

    <script type="application/javascript">
        $(function() {
            //logical model of a user
            var User = Backbone.Model.extend({});

            //visual representation of a user
            var CurrentUserView = Backbone.View.extend({
                render: function() {
                    this.el = ich.user(this.model.toJSON());
                    return this;
                }
            })

            //create a user and drop its representation into the DOM
            var currentUser = new User({username: "hello world"});
            var view = new CurrentUserView({model: currentUser});
            $('.content').append(view.el.render());
        });
    </script>
</head>
<body>
    <div class='content'>
        <p>The user representation should show up below this paragraph</p>
    </div>

    <!--ICanHaz user template -->
    <script id="user" type="text/html">
        <ul class="user">
            <li><a href="#">{{ username }}</a></li>
            <li><a href="#" id="logout">logout</a></li>
        </ul>
    </script>
</body>
</html>

不幸的是,当我在 Firefox 中加载此页面时,用户表示不会显示在 .content div 中,并且错误消息会SyntaxError: JSON.parse: unexpected character显示在 Web 控制台中。

该问题似乎与 CurrentUserView 有关,因为以下代码正是我想要的:

$(function() {
    //logical model of a user
    var User = Backbone.Model.extend({});

    //create a user and drop its representation into the DOM
    var currentUser = new User({username: "hello world"});
    $('.content').append(ich.user(currentUser.toJSON()));
});

这里发生了什么?

4

2 回答 2

1

After a good night's sleep and a second pass at the code, it looks like I had downloaded the json library instead of the required json2 library. Everything is working as expected now.

于 2013-01-15T13:28:45.720 回答
1

不知道为什么这会给你一个解析错误,但我认为$('.content').append(view.el.render());应该是$('.content').append(view.render().el);.

于 2013-01-15T03:36:05.303 回答