2013-07-17 8 views

risposta

5

Il costruttore Callback può passare il this da JavaScript. Secondo il API docs for Callback:

new Callback.many(Function f, {bool withThis: false}) 
new Callback.once(Function f, {bool withThis: false}) 

Ecco un esempio:

codice

Dart:

import 'dart:html'; 
import 'package:js/js.dart' as js; 

void main() { 
    var greeter = js.context['greeter']; 
    var msg = greeter['greet']('Bob'); 
    greeter['doCoolStuff'] = new js.Callback.many(doCoolStuff, withThis: true); 
} 

doCoolStuff(jsThis) { 
    print(jsThis['msg']); 
} 

Avviso l'uso di withThis: true durante la creazione della funzione di richiamata. Il this da JavaScript viene passato come primo argomento della funzione di callback. In questo caso, gli ho dato un nome di jsThis. Codice

JavaScript:

function Greeter() { 
    this.msg = 'hello'; 

    var that = this; 
    document.getElementById('clickme').addEventListener('click', function() { 
    that.doCoolStuff(); 
    }); 
} 

Greeter.prototype.greet = function(name) { 
    return this.msg + ' ' + name; 
} 

var greeter = new Greeter(); 

document.getElementById('clickme').addEventListener('click', function() { 
    greeter.doCoolStuff(); // comes from Dart land 
}); 
Problemi correlati