What is the Dart “Expando” feature about, what does it do?

后端 未结 3 953
灰色年华
灰色年华 2020-12-30 00:23

Have been seeing the term \"Expando\" used recently with Dart. Sounds interesting. The API did not provide much of a clue to me.

An example or two could be most he

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 01:05

    Expandos allow you to associate objects to other objects. One very useful example of this is an HTML DOM element, which cannot itself be sub-classed. Let's make a top-level expando to add some functionality to an element - in this case a Function signature given in the typedef statement:

    typedef CustomFunction(int foo, String bar);
    
    Expando domFunctionExpando = new Expando();
    

    Now to use it:

    main(){
       // Assumes dart:html is imported
       final myElement = new DivElement();
    
       // Use the expando on our DOM element.
       domFunctionExpando[myElement] = someFunc;
    
       // Now that we've "attached" the function to our object,
       // we can call it like so:
       domFunctionExpando[myElement](42, 'expandos are cool');
    }
    
    void someFunc(int foo, String bar){
      print('Hello. $foo $bar');
    }
    

提交回复
热议问题