繁体   English   中英

视图内部的视图中的Backbone.js触发事件

[英]Backbone.js firing event from a view inside a view

有一些麻烦使下面的代码无法正常工作。

我试图从具有自己的事件对象的渲染子视图中触发事件。

是否可以通过简单的方式做到这一点?

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();

有任何想法吗??

MainViewinitialize创建subView ,由于尚未呈现MainView,因此#subview元素在DOM中尚不存在。 因此,在DOM 之外创建了一个新的<div> 您需要先渲染MainView然后再创建SubView 可以MainViewrender()但我认为以下操作更简单:

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()上创建模板,而不是在每个render()上重新编译。

暂无
暂无

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

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