Backbone.js:动态添加未触发的事件

Jan*_*ick 1 events backbone.js

我正在尝试Backbone.js和相处,但我有一个问题.

让我们说我有一个根元素和一个子元素.

加载文档时,我创建3个"根"实例.根实例附加标记.每个根实例创建一个创建一个的子实例

  • ul标签中的标签.

    现在我希望子实例附加和onclick事件到

  • 标签.不幸的是,它不会起作用.

    我创造了一个小提琴:

    http://jsfiddle.net/Fluxo/sEjE5/17/

    var child = Backbone.View.extend({
        template: _.template('<li>Item '+count+'</li>'),
        events: {
            'click li': function() {
             alert('listitem Click Child Element');   
            }
        },
        initialize: function() {
          _.bindAll('render');  
         this.render();   
        }, render: function() {
            this.$el.html(this.template())
        }
    });
    
    var root = Backbone.View.extend({
        template: _.template('<div><h3>List</h3><p /><ul></ul><hr />'),
        events: {
            'click li': function() {
             alert('listitem Click - Root Element');   
            }
        },
        initialize: function() {
            _.bindAll('render');
            this.render();
        },
        render: function() {
            this.$el.html(this.template());
            $('body').append(this.el);
            var item = new child();
            this.$el.find('ul').append(item.$el.html());
    
        }
    });
    
    Run Code Online (Sandbox Code Playgroud)

    在根元素中创建的事件将触发,但不会触发子元素中的事件.

    我做错了吗?

  • mu *_*ort 5

    你做错了两件事.

    首先,你child是一个<li>,它不包含<li>:

    template: _.template('<li>Item '+count+'</li>'),
    events: {
        'click li': ...
    },
    
    Run Code Online (Sandbox Code Playgroud)

    所以你的click li活动不会做任何事情.事件绑定到视图el使用delegate:

    delegateEvents delegateEvents([events])

    使用jQuery的delegate函数为视图中的DOM事件提供声明性回调.[...]省略将selector事件绑定到视图的根元素(this.el)的原因.

    因此,如果要将单击处理程序直接绑定到视图el而不是其子项之一,则需要省略选择器:

    events: {
        'click': ...
    }
    
    Run Code Online (Sandbox Code Playgroud)

    接下来的问题是你实际上没有将child元素插入到DOM中,而是复制HTML:

    this.$el.find('ul').append(item.$el.html());
    
    Run Code Online (Sandbox Code Playgroud)

    通过附加item.$el.html()而不是item.el,您将正确的HTML作为字符串抓取并插入该HTML但是您丢失了该过程中的事件; 事件绑定到DOM对象item.el,而不是HTML字符串.你可以通过追加来解决这个问题item.el:

    this.$el.find('ul').append(item.el);
    // Or you could say, the two approaches are the same
    this.$('ul').append(item.el);
    
    Run Code Online (Sandbox Code Playgroud)

    演示:http://jsfiddle.net/ambiguous/K76JM/(或http://jsfiddle.net/ambiguous/kFxHQ/)