繁体   English   中英

骨干视图事件未触发

[英]Backbone View Events are not Firing

我扩展了一个模态对话框类,以显示带有一些按钮的表单。 这是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"
    }
});

出于某种原因,当我单击按钮时,dismiss事件永远不会触发。 这里发生了什么?

您尚未为视图定义el或tagName。 如果未声明上述任何一项,则Backbone默认将委托事件分配给div。 然后,在您的Initialize函数中,显式设置el,并用附加的事件处理程序覆盖el。 尝试将您的部分设置为tagName并将其从element属性中删除。 然后将您的元素附加到this.el。 抱歉,没有提供代码示例,但我在手机上书写。

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

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

是在jQuery文档准备功能?

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

暂无
暂无

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

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