简体   繁体   中英

Backbone.js can't catch trigger event

Hy, so I'm trying to catch a triggered event, but it looks like i'm missing something:

So i have backbone view, and two plane old javascript objects, one is a "controller" and one is my "app" object, and it looks like this:

// View
SearchView = Backbone.View.extend({
    ...

    events: {
        'keyup .input' : 'search'
    },

    search: function (e) {

        var keyCode = e.keyCode || e.which;

        this.trigger("search:auto", keyCode);
    }
});

// Controller
SearchController = function (options) {
    ...

    this.view = options.view;

    this.view.on("search:auto", this.search, this);

    this.search = function () {
        console.log('great');
    };
};

// App 
App = function() {
    ...

    this.views = {
        searchView : new SearchView()
    };

    new SearchController({
        view: this.views.searchView
    });

    this.start = function() {
        ...
    };
}

new App().start();

And the problem is, that i want to catch the event triggered by the view in the controller, but somehow its not working, i knew to Backbone, maybe i missed something.

Thanks for any help.

Ok, so at last i figured it out, the problem was the order, the event was registered before i declared my function, this is the correct order:

// Controller
SearchController = function (options) {
    ...

    this.view = options.view;

    this.search = function () {
        console.log('great');
    };
    this.view.on("search:auto", this.search, this);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM