简体   繁体   中英

dynamic el value in backbone.js

I would like to use a value such as post-header-id-23 for an el id value. I was just going to use jQuery like this:

$('#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. Alternatively, it looks like something like:

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

but how would I set this up in the render function? 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; unfortunately you can't just give Backbone a selector and expect it to magically stay up to date.

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:

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

As of 0.9.9 version

When declaring a View, options, el and tagName may now be defined as functions, if you want their values to be determined at runtime.

Something like this should do it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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