骨干视图事件没有触发

Backbone View Events are not Firing

本文关键字:事件 视图      更新时间:2023-09-26

我有一个模态对话框类,我正在扩展,以显示一些按钮的形式。这是ModalView视图:

App.ModalView = Backbone.View.extend({
    events: {
        "click .dismiss": "dismiss"
    },
    element: "<section class='modal'><div class='overlay'></div><div class='content'></div></section>",
    initialize: function () {
        this.el = $(this.element);
        this.setupElement();
        this.bindContext();
        this.extendEvents();
        this.render();
        this.miscellaneous();
    },
    bindContext: function () {
        _.bindAll(this, "dismiss", "render", "setBoxStyle");
    },
    setupElement: function () {
        this.template = $("#modal-template");
    },
    miscellaneous: function () {},
    extendEvents: function () {},
    render: function () {
        $(this.el).find(".content").html(this.template.html());
        $("body").append(this.el);
        this.setBoxStyle();
        if (this.options.content) {
            $(this.el).find(".content").html(this.options.content);
        }
    },
    getMargin: function (width, height) {
        var top, left;
        width = parseFloat(width);
        height = parseFloat(height);
        top = Math.max(0, Math.round((window.innerHeight - height) / 2));
        left = Math.max(0, Math.round((window.innerWidth - width) / 2));
        return top + "px " + left + "px";
    },
    setBoxStyle: function () {
        var css = this.options.css || {};
        var el = $(this.el).find(".content");
        el.css(css);
        var width = el.outerWidth();
        var height = el.outerHeight();
        css.margin = this.getMargin(width, height);
        el.css(css);
    },
    dismiss: function () {
        this.remove();
    }
});

这是扩展视图:

App.AddRecordView = App.ModalView.extend({
    setupElement: function () {
        this.template = $("#add-record-template");
    }
});

模板:

<script type="text/template" id="add-record-template">
    <h1>Add Record</h1>
    <button class="green save">Save Record</button>
    <button class="cancel dismiss">Cancel</button>
</script>
下面是我初始化视图的方法:
this.addRecordView = new App.views.addRecord({
    model: this.model,
    css: {
        width: "400px"
    }
});

由于某些原因,当我单击按钮时,解散事件从未触发。这是怎么回事?

您还没有为视图定义el或tagName。如果上面没有声明,Backbone默认将委托事件分配给div。然后在初始化函数中显式设置el,用附加的事件处理程序覆盖el。尝试将section设置为tagName,并将其从元素属性中移除。然后将元素追加到this.el。对不起,没有提供一个代码的例子,但我在我的手机上写。

没有适当的代码,我只能猜测,但是这种错误通常是因为视图的代码是在dom准备好之前声明的。

你能告诉我们你在哪里启动你的应用程序吗?

是在一个jquery文档准备函数?

$(function(){
    this.addRecordView = new App.views.addRecord({
        model: this.model,
        css: {
            width: "400px"
        }
    });
});