gpt4 book ai didi

javascript - 主干 View 事件绑定(bind)较晚

转载 作者:行者123 更新时间:2023-12-02 19:29:48 25 4
gpt4 key购买 nike

我在 View 初始化时触发事件时遇到问题。如果我使用 setTimeout 调用该事件,则会触发该事件。但是,该事件不会在 View 初始化时触发。

/*global app */

define([
'handlebars',
'text!templates/achievements.html'
], function (Handlebars, AchievementsTemplate) {
"use strict";
var AchievementsView = Backbone.View.extend({

achievementsTemplate: Handlebars.compile(AchievementsTemplate),

initialize: function () {
var el = this.render(this.model);
this.$weekFilter = $(el).find(".challenge-nav li.open a");
this.model.bind('change', this.resetFilters, this);
this.resetFilters();
},
render: function (model) {
this.$el.html(this.achievementsTemplate(model.toJSON()));
return this.$el;
},
events: {
"click .challenge-nav li a": "filterAchievements"
},
resetFilters: function () {
this.$weekFilter.first().trigger("click");
},
filterAchievements: function (ev) {
console.log("test");
}
});
return AchievementsView;
});

上面没有调用resetFilters函数,但是如果我执行setTimeout,就会调用该函数。唯一的猜测是事件发生得很晚?有什么想法吗?

Hi All,

/*global app */

define([
'handlebars',
'text!templates/achievements.html'
], function (Handlebars, AchievementsTemplate) {
"use strict";
var AchievementsView = Backbone.View.extend({

achievementsTemplate: Handlebars.compile(AchievementsTemplate),

initialize: function () {
var el = this.render(this.model);
this.$weekFilter = $(el).find(".challenge-nav li.open a");
this.model.bind('change', this.resetFilters, this);
this.resetFilters();
},
render: function (model) {
this.$el.html(this.achievementsTemplate(model.toJSON()));
return this.$el;
},
events: {
"click .challenge-nav li a": "filterAchievements"
},
resetFilters: function () {
var self = this;
setTimeout(function () {
self.$weekFilter.first().trigger("click");
},100);
},
filterAchievements: function (ev) {
console.log("test");
}
});
return AchievementsView;
});

最佳答案

如果 $weekFilter DOM 元素不是成就模板的一部分,因此当您初始化小部件时它位于 DOM 中,那么问题是所有事件初始化后被委托(delegate)。参见 Backbone 来源:http://backbonejs.org/docs/backbone.html#section-145

为什么不将 this.resetFilters() 移至 render()

关于javascript - 主干 View 事件绑定(bind)较晚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11629686/

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