简体   繁体   English

为什么这个。$ el给出了未定义的错误,但$(this.el)在Backbone视图中的render函数内部工作?

[英]Why this.$el gives undefined error but $(this.el) works inside render function in Backbone view?

I am quite new to backbone.js with little experience in javaScript. 我对于几乎没有javaScript经验的backbone.js很新。 I was trying various backbone tutorial found here and there. 我在这里和那里尝试各种骨干教程。 eg from this tutorial I was trying to learn 例如,从本教程我试图学习

backbone-baby-steps 骨干宝贝步骤

In most of the tutorials like above one, they use following code inside Backbone.View.extend to set the model in html template and then render it, 在上面的大多数教程中,他们使用Backbone.View.extend以下代码在html模板中设置模型,然后渲染它,

render: function() {
    var tmpl = _.template(this.template);
    this.$el.html(tmpl(this.model.toJSON()));
    return this;
    }

but when I run the code in chrome debugger it says this this.$el is undefined. 但是当我在chrome调试器中运行代码时,它会说明这this.$el未定义。 I searched a lot but didn't get the solution, then I modified the code by own and it worked, 我搜索了很多,但没有得到解决方案,然后我自己修改了代码,它工作,

$(this.el).html(tmpl(this.model.toJSON()));

I'm using cdnjs hosted libraries for backbone, underscore and jquery. 我正在使用cdnjs托管库来实现主干,下划线和jquery。

I want to know why every backbone tutorial on internet is using this.$el version but it doesn't work for me? 我想知道为什么互联网上的每个骨干教程都使用this.$el版本,但它对我不起作用?

And also, when I use the the library(backbone, underscore etc.) files provided by the tutorials instead of hosted one, chrome debugger gives various errors in libraries, why? 而且,当我使用教程提供的库(主干,下划线等)文件而不是托管文件时,chrome调试器会在库中出现各种错误,为什么?

As per the change log specified in the docs , $el property - a cached jQuery (or Zepto) reference to the view's element was added in version 0.9.0 . 根据docs中指定的更改日志, $el属性 - 在0.9.0版本中添加了a cached jQuery (or Zepto) reference to the view's element Try upgrading the version of backbone you're using to 0.9.0 or above. 尝试将您使用的backbone版本升级到0.9.0或更高版本。 It should work after that. 它应该在那之后工作。

You need to define in your View like below 您需要在视图中定义,如下所示

var ElementView = Backbone.View.extend({
    el: $("#picker")
}

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

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