简体   繁体   English

骨干主体视图未渲染

[英]backbone body view not rendering

I've got a stupid mistake somewhere and I cannot make a base backbone view get rendered. 我在某个地方犯了一个愚蠢的错误,无法渲染基本的主干视图。 Can someone please point me what's wrong in this code? 有人可以指出这个代码有什么问题吗?

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 the console.log is empty. PS console.log为空。

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 jsBin

While the conventional way is to extend Backbone.view, and instantiate new instances of a view (per Jack's answer), you can get what you want (instantiating a simple view) by wrapping Backbone.View.extend in parens: 尽管常规方法是扩展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 jsbin

This can be helpful for "one off" views/routers/etc, that you don't intend reinstantiating multiple times. 这对于不打算多次实例化的“一次性”视图/路由器/等很有帮助。 The method in Jack's answer is more readable (and useful) for most cases. 在大多数情况下,杰克答案中的方法更具可读性(并且很有用)。

You have to actually create that view. 您必须实际创建该视图。

Before render: function(){} 渲染之前:function(){}

Add

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

and when you want to load the page / view use this 当您要加载页面/视图时,请使用此

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

Although normally a view variable should be extended from Backbone view. 尽管通常情况下,应从Backbone视图扩展视图变量。

So instead of "var view" ... it should be something like window.myView = Backbone.View.extend( { } ) 因此,与其说是“ var view”,不如说是window.myView = Backbone.View.extend({})

See http://backbonejs.org/#View 参见http://backbonejs.org/#View

It's easier to manage when the views represent objects. 当视图表示对象时,管理起来更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM