骨干视图事件绑定较晚

时间:2012-07-24 11:15:46

标签: javascript events backbone.js

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

/*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;
});

1 个答案:

答案 0 :(得分:2)

如果$weekFilter DOM元素不是Achievements模板的一部分,那么当你initialize小部件时它就在DOM中,那么问题是所有事件都是在初始化之后委托的。请参阅主干来源:http://backbonejs.org/docs/backbone.html#section-145

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