2012-03-07 12 views
2

以下のコードを動作させるのに問題がありますか?Backbone.jsビュー内のビューからイベントを起動する

私は、独自のイベントオブジェクトを持つレンダリングされたサブビューからイベントを発生させようとしています。

これを簡単に行うことはできますか?

var SubView = Backbone.View.extend({ 
    events: { 
     'click .subview-item a': 'test' 
    }, 
    el: '#subview', 
    test: function() { 
     console.log('please print this...'); 
    }, 
    initialize: function() { 
     this.template = '<div class="subview-item"><a href="#">Clickable Subview</a></div>' 
    }, 
    render: function(){ 
     $(this.el).html(_.template(this.template)); 
     return this; 
    } 
}); 

var MainView = Backbone.View.extend({ 
    el: $('#content'), 
    initialize: function(){ 
     this.template = '<h1>Hello</h1><div id="subview"></div>'; 
     this.subView = new SubView(); 
    }, 
    render: function(){ 
     $(this.el).html(_.template(this.template)); 
     this.subView.render(); 
     return this; 
    } 
}); 

var mainView = new MainView({}); 
mainView.render(); 

答えて

6

あなたは、あなたがまだレンダリングされていないのでMainViewさんinitialize内部subView#subview要素はまだ、あなたのDOMに存在しないMAINVIEWを作成する場合。したがって、新しい<div>の外側に作成されます。 DOM。 SubViewを作成する前に、まずMainViewをレンダリングする必要があります。

var SubView = Backbone.View.extend({ 
    events: { 
     'click .subview-item a': 'test' 
    }, 
    el: '#subview', 
    test: function() { 
     console.log('please print this...'); 
    }, 
    initialize: function() { 
     this.template = _.template('<div class="subview-item"><a href="#">Clickable Subview</a></div>'); 
    }, 
    render: function() { 
     this.$el.html(this.template); 
     return this; 
    } 
}); 

var MainView = Backbone.View.extend({ 
    el: $('#content'), 
    initialize: function() { 
     this.template = _.template('<h1>Hello</h1><div id="subview"></div>'); 
    }, 
    render: function() { 
     this.$el.html(this.template); 
     return this; 
    } 
}); 

var mainView = new MainView(); 
mainView.render(); 
var subView = new SubView(); 
subView.render(); 

this.$elを使用して、テンプレートを作成するinitialize()ではなく、すべての再コンパイルのようないくつかのことを修正するために自由を取った:あなたMainViewrender()の内側が、以下は、私が考える単純であることを行うことができますrender()

関連する問題