Search code examples
javascripthtmlbackbone.jsbrowser-extension

How to manually call Backbone.js view's method


I'm writing a browser extension for a site that uses Backbone.js. Its pertinent code looks like the following (names have been changed to protect the innocent):

var BigContainer = BigContainer || {};
(function($, exports) {
    var Thing = Backbone.View.extend({
    ...

    useful_func: function() {
        // Does something I need to call
    },
    ...
});

(function($, exports) {
    BigContainer.BaseView = Backbone.View.extend({
    ...
    render: function() {
        this.local_thing = new Thing({
            el: '.local_thing'
        });
    }
    ...
});

I am also inserting some code in a <script> block to listen for postMessage() calls I make from my extension's injected javascript file. I would like to be able to call useful_func from there, but can't figure out how, or if I'm even supposed to (and if not, then how I can arrive at the same result).

As an example, I've tried the following references, all of which show up as undefined:

  • BigContainer.BaseView.$local_thing
  • BigContainer.BaseView.local_thing
  • Thing
  • document.getElementsByClassName('local_thing')[0].useful_func

Importantly, since I'm writing an extension for a site I don't own, I can't modify the site's Backbone.js code to help myself out. I need to work with what's there.


Solution

  • With the line BigContainer.BaseView = Backbone.View.extend({, you are defining a new View type called BaseView, but it is only the definition. What you need is the actual instance of the view in your code. That would be somewhere where you do new BaseView (in this case, it's the following:)

    // Where view is created
    (function($, undefined) {
        BigContainer.OtherThing = {
        ...
        create: function(config, params) {
            this.view = new BigContainer.BaseView(...);
        }
        ...
    })
    

    With that found, you would do something like this:

    // Your code, reach into that instance and its subview, and call 'usefulFunc'.
    BigContainer.OtherThing.view.local_thing.useful_func();