3

我正在尝试设置 Backbone 应用程序。下面的代码给出了以下错误:

未捕获的类型错误:对象 # 没有“附加”方法

define(
    [
        'jQuery',
        'Underscore',
        'Backbone',
        'text!templates/start.html'
    ],

    function ($, _, Backbone, startTemplate)
    {
        var StartView = Backbone.View.extend({

            // properties
            el: $('#container'),

            initialize: function ()
            {
                this.render();
            },

            render: function ()
            {
                var template = _.template( startTemplate );
                this.el.append( template );
            }
        });

        return new StartView;
    }

);

但这有效(参见“渲染”功能):

define(
    [
        'jQuery',
        'Underscore',
        'Backbone',
        'text!templates/start.html'
    ],

    function ($, _, Backbone, startTemplate)
    {
        var StartView = Backbone.View.extend({

            // properties
            el: $('#container'),

            initialize: function ()
            {
                this.render();
            },

            render: function ()
            {
                var template = _.template( startTemplate );
                $(this.el).append( template );
            }
        });

        return new StartView;
    }

);

我将 $('#container') 作为 'el' 属性传递,所以我认为这应该可以正常工作。为什么我必须为此再次使用 jQuery 表示法。$(this.el) 而不是 this.el

非常感谢提前!

4

1 回答 1

13

在 Backbone 中,您只需将 ID 或类名提供给el

el: '#container'

然后,this.el引用 DOM 元素,并且(如果您使用最新的 Backbone),this.$el引用 jQuery 对象。

如果您的 Backbone 是最新的,则不需要 $(this.el)

于 2012-06-26T13:51:21.670 回答