簡體   English   中英

主干事件處理程序不起作用

[英]Backbone event handler doesn't work

我有兩個視圖——一個布局視圖,它是頂級的,一個新的表單視圖,它充當布局的子視圖並在其中呈現。 我在表單視圖中有一個事件處理程序,它應該根據輸入的數據創建我的模型的一個新實例。

這是布局視圖:

var LayoutView = Backbone.View.extend({
    el: "#layout",
    render: function (view) {
        this.child = view;
        if (this.child) {
            this.child.remove();
        }
        this.$el.html(this.child.render().el);
        return this;
    }
});

這是我的表單視圖:

var ResumeForm = Backbone.View.extend({
    events: {
        'click #create': 'createResume'
    },
    initialize: function () {
        this.template = _.template($('#new-resume').html());
    },
    render: function () {
        this.$el.html(this.template());
        return this;
    },
    createResume: function () {
        // getting values from template inputs and saving them to model
        var resume = new Resume({
            profession: $('#profession').val(),
            firstName: $('#firstname').val(),
            lastName: $('#lastname').val()
        });
        // saving a new model to collection instance
        resumes.add(resume);
        resume.save(null, {
            success: function (res) {
                console.log("POST resume id " + res.toJSON().id);
            },
            error: function () {
                console.log("Failed to POST");
            }
        });
    }
});

我的表單視圖完美地呈現在我的布局視圖中,但是當我輸入值並單擊#create按鈕時,沒有任何反應——既不保存模型,也不記錄我的createResume方法中的任何錯誤錯誤。 我懷疑在布局視圖中渲染表單視圖時,這行this.$el.html(this.child.render().el); 只是銷毀所有事件偵聽器,因為如果我將這些偵聽器添加到布局視圖中,它就可以工作。

有什么方法可以解決這個問題嗎?

Backbone 的視圖remove函數取消委托綁定到el的事件。

從帶注釋的來源

 remove: function() { this._removeElement(); this.stopListening(); return this; }, _removeElement: function() { this.$el.remove(); },

這與 jQuery .remove()函數有關(重點是我的):

.empty()類似, .remove()方法從 DOM 中取出元素。 當您想要刪除元素本身以及其中的所有內容時,請使用.remove() 除了元素本身之外,所有與元素關聯的綁定事件和 jQuery 數據都將被刪除 要在不刪除數據和事件的情況下刪除元素,請改用.detach()

如果在重用視圖之前調用remove ,則需要手動調用this.delegateEvents()以重新綁定events哈希中的events並重新連接視圖通過this.listenTo(...)偵聽的任何事件。

但是重用視圖的最佳方法是,無需調用remove調用stopListening ,您可以使用setElement取消委托事件,並將視圖元素更改為傳遞的元素,然后重新委托事件。

 setElement: function(element) { this.undelegateEvents(); this._setElement(element); this.delegateEvents(); return this; },

你的LayoutView會變成這樣:

var LayoutView = Backbone.View.extend({
    el: "#layout",
    render: function(view) {
        // if the view is different, make sure to undelegate the old view.
        if (this.child && this.child !== view) this.child.undelegateEvents();
        this.child = view;
        this.child.setElement(this.$el).render();
        return this;
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM