1

我在某处犯了一个愚蠢的错误,我无法渲染基本主干视图。有人可以指出这段代码有什么问题吗?

var view = new Backbone.View({
    el: 'body',
    template: '<p>this is my new template</p>',
    render: function() {
        console.log('rendering myself');
        this.$el.html(this.template);
        return this;
    }
});

view.render();

PS console.log 是空的。

4

3 回答 3

5

You're syntax is a bit off, you should be first defining your view and then instantiating it.

//define view 
var MyView = Backbone.View.extend({
    el: 'body',
    template: '<p>this is my new template</p>',
    render: function() {
        console.log('rendering myself');
        this.$el.html(this.template);
        return this;
    }
});

//create view instance
var view = new MyView();
view.render();

jsBin

于 2013-08-14T19:01:10.310 回答
2

虽然传统的方法是扩展 Backbone.view,并实例化视图的新实例(根据 Jack 的回答),但您可以通过将 Backbone.View.extend 包装在括号中来获得所需的内容(实例化一个简单的视图):

var view = new (Backbone.View.extend({
    el: 'body',
    template: '<p>this is my new template</p>',
    render: function() {
        console.log('rendering myself');
        this.$el.html(this.template);
        return this;
    }
}));

view.render();

jsbin

这对于您不打算多次重新实例化的“一次性”视图/路由器/等很有帮助。在大多数情况下,杰克答案中的方法更具可读性(且有用)。

于 2013-08-14T19:23:31.900 回答
0

您必须实际创建该视图。

渲染前:function(){}

添加

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

当你想加载页面/视图时使用这个

$(document).ready( function(){
     new view({"el:body});
});

尽管通常应该从 Backbone 视图扩展视图变量。

因此,而不是“var view”......它应该类似于 window.myView = Backbone.View.extend( { } )

http://backbonejs.org/#View

当视图代表对象时更容易管理。

于 2013-08-14T19:00:28.773 回答