好的,我有一个父 View ,该 View 具有一个click事件,该事件呈现一个 subview 。在此 subview 中,我正在尝试验证然后提交的表单。所以我的父 View 看起来像这样:

var MapView = Backbone.View.extend({
    el: '.body',
    template: _.template(MapTemplate),
    render: function() {
        ...
    },
    events: {
        'click #log-pane-title': 'loadLogView'
    },
    loadLogView: function() {
        var eventLogView = new EventLogView({
            id: properties._id
        });

        eventLogView.render();
    }
});

我的 subview 看起来像这样:
var EventLogView = Backbone.View.extend({
    el: '#eventlog',
    logform: new NewLogForm({
                template: _.template(AddLogTemplate),
                model: new LogModel()
            }).render(),
    render: function() {
        // Render the form
        $("#addtolog").html(this.logform.el);
    },
    events: {
        'submit #addlogentry': 'test'
    },
    test: function() {
        alert('inside eventlogview');
        return false;
    }
});

我面临的问题是test()永远不会触发。为了进行调试,我通过以下方式确保了Submit事件甚至被触发:
$('#addlogentry').on('submit', function() {
    alert( "submit firing" );
    return false;
});

render()EventLogView中。这确实会触发,所以我不确定发生了什么以及为什么test()没有触发。

最佳答案

为避免范围问题,所有events委派的范围都限定在Backbone中的el View 中。

因此,您的#addlogentry按钮应该位于EventLogView el内部。

而且您在render中的健全性检查应类似于以下内容,以模仿Backbone在内部的工作方式:

this.$el.on('submit', '#addlogentry', function() {
    alert( "submit firing" );
    return false;
});

07-24 09:38
查看更多