Explosion Pills
Explosion Pills

Reputation: 191729

Trigger view event with jQuery

I have a Backbone View with simple events:

Backbone.View.extend({
    events: {
        "change #id": "idChanged"
    },
    idChanged: function () {}
    initialize: function () {
        /* construct HTML */

        $("#id").trigger("change");
    }
});

However this does not fire the idChanged event. When I change #id with the browser it does fire. How can I trigger the Backbone View event?

Upvotes: 0

Views: 123

Answers (3)

Yurui Zhang
Yurui Zhang

Reputation: 2232

a couple of things in your code.

1 I don't think you defined your events correctly.

It should be a hash, or a function that returns a hash, like so:

events: {
    "change #id": "idChanged"
}

2 a few typos like "function" and missing comma

then, to make the events work, the defined #id element must be inside the view's el. If the element is outside of the view, it's not gonna work.

also, you cannot trigger that in initialize, because before that function is executed, the view is not fully initialized yet. :)

here's a working example:

http://jsfiddle.net/3KmzQ/

Upvotes: 1

David Sulc
David Sulc

Reputation: 25994

That's because the events hash will be bound to the view when it gets rendered, which happens after the initialize code gets run. Try calling the desired callback directly:

Backbone.View.extend({
    events: function () {
        "change #id": "idChanged"
    },
    idChanged: function () {}
    initialize: function () {
        /* construct HTML */

        this.idChanged();
    }
});

Upvotes: 1

Jolin
Jolin

Reputation: 1

You used "extend". Same code should apply to Backbone.view.Object( {....} ) Specify the object that you would like to fire events at.

Backbone.View.Ojbect(
  {
    events: function () {

    "change #id": "idChanged"
    },

idChanged: funciton () {}

initialize: function () {
    /* construct HTML */
    $("#id").trigger("change");
}
}
);

That is, try not to extend.

Upvotes: 0

Related Questions