简体   繁体   English

如何手动调用Backbone.js视图的方法

[英]How to manually call Backbone.js view's method

I'm writing a browser extension for a site that uses Backbone.js . 我正在为使用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. 我还在<script>块中插入一些代码,以侦听我从扩展程序注入的javascript文件发出的postMessage()调用。 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). 我希望能够从那里调用useful_func ,但是却不知道该怎么做,或者我是否应该这样做(如果没有,那么我怎么才能得到相同的结果)。

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. 重要的是,由于我正在为自己不拥有的网站编写扩展程序,因此无法修改该网站的Backbone.js代码以帮助自己。 I need to work with what's there. 我需要处理其中的内容。

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:) 在行BigContainer.BaseView = Backbone.View.extend({ ,您正在定义一个称为BaseView的新View类型,但这只是定义。您需要的是代码中该视图的实际实例。在其中执行new BaseView (在这种情况下,为以下位置:)

// 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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