简体   繁体   English

主干.js中的动态el值

[英]dynamic el value in backbone.js

I would like to use a value such as post-header-id-23 for an el id value. 我想为el id值使用诸如post-header-id-23之类的值。 I was just going to use jQuery like this: 我只是要像这样使用jQuery:

$('#post-header-id-' + this.model.id).after(compiled_template);

but it looks like the events don't get wired up. 但看起来事件并没有发生。 Is there a way to fix that so that jQuery selectors don't inhibit normal selectors. 有没有一种方法可以解决此问题,以使jQuery选择器不会禁止普通选择器。 Alternatively, it looks like something like: 另外,它看起来像:

el: $('#post-header-id' + this.model.id ),

but how would I set this up in the render function? 但是我该如何在render函数中设置呢? Or am I doing something else wrong? 还是我做错了其他事?

thx 谢谢

The key thing here is that you have to decide when is the right time to decide what "el" is; 这里的关键是您必须确定何时才是确定“ el”是什么的正确时间。 unfortunately you can't just give Backbone a selector and expect it to magically stay up to date. 不幸的是,您不能仅仅给Backbone一个选择器,并期望它神奇地保持最新状态。

So, bearing that in mind, if "render" is the right time to set your el (and usually either initialize or render is the right spot), you just need to use Backbone's (somewhat new-ish) setElement function: 因此,请记住,如果“ render”是设置el的正确时间(通常是初始化或渲染是正确的位置),则只需要使用Backbone的setElement函数(有些新颖)即可:

var SomeView = Backbone.View.extend({
    render: function() {
        this.setElement($('#post-header-id' + this.model.id));
        return this;
    }
})

As of 0.9.9 version 从0.9.9版本开始

When declaring a View, options, el and tagName may now be defined as functions, if you want their values to be determined at runtime. 声明视图时,如果希望在运行时确定其值,则可以将options,el和tagName定义为函数。

Something like this should do it: 这样的事情应该做到:

id: function() {
  return '#post-header-id' + this.model.id
}

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

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