0

I am having problems triggering an event on the initialization of a view. If I use setTimeout to call the event, the event is fired. However the event is not fire on the view's initialization.

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

The above does not call the resetFilters function, but if I do a setTimeout, the function is called. Only guess is that the events are bound very late? Any Idea?

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;
});
4

1 回答 1

2

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

你为什么不this.resetFilters()搬去render()

于 2012-07-24T13:27:54.230 回答