简体   繁体   中英

Calling a method from inside a view without using “this” keyword?

My backbone code seems to have a crazy number of this.methodCall() type of invocations and I'd love to be able to drop the this , and just call methodCall() directly from inside the View.

See the below code:

app.Main = Backbone.View.extend({

    el: '#main-div',

    // how do I call this function without invoking "this"?
    setPageCookies: function () {
        console.log('setting page cookies called!');
    },

    initialize: function () {
        // saw this online as a possible solution, but only seems to affect the scope of "this" 
        _.bindAll(this, 'setPageCookies');

        // this works:
        this.setPageCookies();

       // HOWEVER, I'd like to be able to call it like this instead:
       setPageCookies();

    }

});

Firstly - this.setPageCookies() and setPageCookies() have drastically different meanings.

The way to achieve calling setPageCookies() without this would be to make setPageCookies a function declaration:

function setPageCookies() {

}

Backbone.View.extend({ 
  setPageCookies: setPageCookies,
  initialize: function() {
    setPageCookies()
  }
});

However, now you can't use this instead of setPageCookies - unless you use bind , or unless you write a complicated wrapper around setPageCookies: setPageCookies which takes the this value and passes it as a first argument.. or something. Which makes me ask - why do you want to achieve 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