使用下划线模板在 backbone.js 中呈现

Rendering in backbone.js with underscore templates

我尝试使用下划线模板呈现项目列表。但它什么也没显示。

我尝试创建 2 个视图,一个是任务,一个是任务列表,但我一直坚持使用模板。

我以为当你这样做时数据会映射模板变量this.$el.html(template_var)?

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>

        <script type="text/template" id="task_list">
            <li><%=title%></li>
            <li><%=priority%></li>
        </script>

        </script>

<script type="text/javascript">
        (function(){

        window.App = {
            Models:{},
            Collections:{},
            Views:{}
        };

        window.template = function(id){
            return _.template( $('#' + id).html() );
        }
        

        App.Models.Task = Backbone.Model.extend({
                title: 'default',
                priority: 1
        });

        App.Collections.Task = Backbone.Collection.extend({
            model: App.Models.Task
        });

        App.Views.Task = Backbone.View.extend({
            template: template('task_list'),
            render(){
                var template = this.template( this.model.toJSON() );
                console.log(template)
                this.$el.html(template);
                return this;
            }
        })

        App.Views.Tasks = Backbone.View.extend({
            tagName: 'ul',
            render: function(){
                this.collection.each( this.addOne, this);
                return this;
            },
            addOne: function(task){
                var taskView = new App.Views.Task({ model: task})
                taskView.render();
                this.$el.append(taskView.render().el);
            }
        })

        var tasks = new App.Collections.Task([
            {
                    title: 'Go to store',
                    priority: 4
                },
                {
                    title: 'Eat',
                    priority: 3
                },
                {
                    title: 'Sleep',
                    priority: 4
                }
        ])

        var tasksView = new App.Views.Tasks({collection: tasks})
        $('body').html(tasksView.el)

        })()

</script>

</body>
</html>

你们真的很接近,但是有一些小问题。

Backbone 做了很多事情,但它没有为您做的一件事是渲染逻辑,这完全由开发人员决定。所以,你需要:

  • 用于将 HTML 与 JS 逻辑分开的模板。
  • 一个 render 函数,它使用您最喜欢的技术进行渲染,在我们的例子中是 jQuery。

一个 Backbone 视图总是有一个 root DOM element (el),即使它还没有被渲染,如果没有指定 tagName,默认情况下它是一个 div

所以你的任务视图在呈现时看起来像这样:

<div>
    <li>Go to store</li>
    <li>4</li>
</div>

我稍微更改了模板即可使用。


我将 CSS 移回了 HEAD 部分。这是一个标准,但并不是真正的问题之一。


模型中的默认属性应在 defaults property 中指定。


像下面这样使用 shorthand syntax 定义函数仅在 ES6 (ECMAScript 2015) 中可用。

render(){

Starting with ECMAScript 2015 (ES6), a shorter syntax for method definitions on objects initializers is introduced. It is a shorthand for a function assigned to the method's name.

要使其成为 compatible with most browser,您应该使用:

render: function() {

您还忘记了在列表视图上调用渲染。

$('body').html(tasksView.el)

应该是:

$('body').html(tasksView.render().el);

由于您的代码在 IIFE 中,您不需要使用 window 使您的应用程序和函数成为全局的,本地 var 就足够了,而且更好编码练习。


<!DOCTYPE HTML>
<html>

<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <!-- CSS should be in the head -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>

<body>



    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="http://underscorejs.org/underscore.js"></script>
    <script src="http://backbonejs.org/backbone.js"></script>

    <script type="text/template" id="task_list">
        <%=title%> (<%=priority%>)
    </script>

    <script type="text/javascript">
        (function() {

            var App = {
                Models: {},
                Collections: {},
                Views: {}
            };

            function template(id) {
                return _.template($('#' + id).html());
            }


            App.Models.Task = Backbone.Model.extend({
                defaults: {
                    title: 'default',
                    priority: 1
                }
            });

            App.Collections.Task = Backbone.Collection.extend({
                model: App.Models.Task
            });

            App.Views.Task = Backbone.View.extend({
                template: template('task_list'),
                tagName: 'li',
                render: function() {
                    var template = this.template(this.model.toJSON());
                    console.log(template)
                    this.$el.html(template);
                    return this;
                }
            });

            App.Views.Tasks = Backbone.View.extend({
                tagName: 'ul',
                render: function() {
                    this.collection.each(this.addOne, this);
                    return this;
                },
                addOne: function(task) {
                    var taskView = new App.Views.Task({
                        model: task
                    })
                    this.$el.append(taskView.render().el);
                }
            });

            var tasks = new App.Collections.Task([{
                title: 'Go to store',
                priority: 4
            }, {
                title: 'Eat',
                priority: 3
            }, {
                title: 'Sleep',
                priority: 4
            }]);

            var tasksView = new App.Views.Tasks({
                collection: tasks
            });
            $('body').html(tasksView.render().el);

        })()
    </script>

</body>

</html>