gpt4 book ai didi

javascript - 更改 el 属性时主干 View 事件未触发

转载 作者:行者123 更新时间:2023-11-29 16:19:21 24 4
gpt4 key购买 nike

我是 Backbone 的新手,正在尝试做一些示例,但我坚持使用这个。我有以下 BackBone View :

CommentBoxView = Backbone.View.extend({
initialize: function () {
this.render();
},
render: function () {
var template = _.template( $("#comment_box_template").html(), {} );
this.el.html(template);
},
events: {
"keypress textarea": "doKeyPress"
},
doKeyPress: function (event) {
console.log(event);
}
});

一切正常,但如果我更换

this.el.html(template);

有了这个:

this.el = $(template).replaceAll(this.el);

根本不会触发按键事件。任何人都可以向我解释为什么会发生以及如何使这段代码有效吗?非常感谢大家。

最佳答案

Backbone 使用 View 的 delegateEvents绑定(bind) jQuery 的方法 delegate调用 View 的 el ,这个 delegate 是处理所有 View 事件的。如果你这样做:

this.el = $(template).replaceAll(this.el);

您丢失了绑定(bind)到 this.eldelegate,您的事件也随之消失。你也会得到你的 this.$elthis.el 不匹配,这也不好。更改 View 的 el 的正确方法是使用 setElement :

setElement view.setElement(element)

If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view's delegated events from the old element to the new one.

所以你应该可以这样做:

this.setElement($(template).replaceAll(this.el));

关于javascript - 更改 el 属性时主干 View 事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12229719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com