Вопрос

I think this should be quiet easy but somehow I cannot figure out how this works.

I have 2 templates in backbone js, which I'd like to place on different positions, but by using the same Backbone.View

HTML

<script type="text/template" id="tmpl1">
<div> template 1 </div>
</script>

<script type="text/template" id="tmpl2">
<div> template 2 </div>
</script>

<div id="firstDiv"></div>

Next Template 

<div id="secondDiv"></div>

JS

TmplView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },
    render: function(){
        var template = _.template( this.$el.html(), {} );
        this.container.append( template );
    },
    container:  $("#firstDiv"),
});

var template1  = new TmplView({ el: $("#tmpl1") } );
var template2  = new TmplView({ el: $("#tmpl2") } );

My question: How to set template2 to container $("#secondDiv")?

I tried var template2 = new TmplView({ el: $("#tmpl2"), container: $("#secondDiv") } );

Please let me know the common way to do so.

Thank you

Это было полезно?

Решение 2

I solved the problem by following solution:

TmplView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },
    render: function(){
        console.log(this.$el);
        var template = _.template( this.$el[0].html(), {} );
        this.$el[1].append( template );
    },
});

var template1  = new TmplView({ el: [$("#tmpl1"), $("#firstDiv" ) ] } );
var template2  = new TmplView({ el: [$("#tmpl2"), $("#secondDiv") ] } );

If anyone might have a better approach, it will be welcome.

Другие советы

Try this :

TmplView = Backbone.View.extend({
initialize: function(){
    this.render();
},
render: function(){
    var template = _.template( this.template, {} );
    this.$el.append( template );
}
});

var template1  = new TmplView({ el: "#firstDiv", template : $('#tmpl1').html() } );
var template2  = new TmplView({ el: "#secondDiv", template : $('#tmpl2').html() } );
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top