문제

I've got two situations where I'm declaring var that = this and I'm wondering if there is a smarter way of handling it with a native function like call() or apply() so I don't have to create an anonymous function?

var that = this;
this.listenTo( foo, 'event', function() {
    that.trigger( 'change' );
});

var that = this;
this.listenTo( foo, 'event', function( bar ) {
    that.add( bar );
});
도움이 되었습니까?

해결책

Function#bind()

So something like this:

this.listenTo( foo, 'event', function() {
    this.trigger( 'change' );
}.bind(this));

this.listenTo( foo, 'event', function( bar ) {
    this.add( bar );
}.bind(this));

다른 팁

Not tested (especialy I think to much binds and this), but how about like this:

this.triggerFn = function(ev) {
    return function() {
        this.trigger(ev);
    }.bind(this);
}.bind(this);

this.addFn = function() {
    return function(bar) {
        this.add(bar);
    }.bind(this);
}.bind(this);

this.listenTo( foo, 'event', this.triggerFn('change'));

this.listenTo( foo, 'event', this.addFn( bar ));

For bind polyfill see that.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top