如何动态修改Backbone View的`el`键?

时间:2012-06-13 12:33:08

标签: backbone.js

我创建了一个主干视图AB

var App = {
    run: function () {
        this.aview = new aView();
        this.bview = new bView();
    }
};

// First View
var aView = Backbone.View.extend({
    el: '#a', 
    render: function () {
       this.$el.html('foobar A');
    }        
});

// Second View
var bView = Backbone.View.extend({
    el: '#b', 
    render: function () {
       this.$el.html('foobar B');

       // want to put `foobar A` content into #c which is inside #b 
       // but aView's el lets it be into #a.
       // One Possible solution would be to create a new instance of aView 
       // and change its `el` 
       var tempaView = new aView({ el: '#c' });
       tempaView.render();  // Now it puts `foobar A` into #c 
       // Or another solution would be to pass a new element as a param to 
       // App.aview.render('#c'); and check whether param is undefined, otherwise
       // the content will be added into #param (in this case #c). 
    }
});


App.aview.render(); // Puts `foobar A` into <body>        
App.bview.render(); // Puts `foobar B` into #b and `foobar A` into #c

所以,我的问题是哪一个是正确的方法? 除此之外,有没有人有更好的解决方案?

1 个答案:

答案 0 :(得分:2)