《Hello Flex 4》笔记——2 ActionScript 3, XML, and E4X

AS3基础, 注意与其它语言的不同点

SESSION 6  Variables, functions, types, and scope

session06/src/model/Task.as

package model { //注意有大括号        
  public class Task {
    public var name:String;  //类型放在最后
    public var something:*;  //星号代表任意类型
    protected var someDate:Date;  
    internal var anInt:int;
    private var _aNumber:Number; 
    
    public function Task(name:String = "") {
      this.name = name;
      something = "Ostrich";      
      someDate = new Date();
      anInt = Math.random() * 10;
      _aNumber = Math.random() * 10;
    }
    public function getDate():Date {
      return someDate;
    }
    public function getAnInt():int {
      return anInt;
    }
    public function get aNumber():Number {   //注意写法,取值时直接用“对象名.aNumber”
      return _aNumber;
    }
    public function set aNumber(value:Number):void {  //注意写法
      _aNumber = value;
    }
  }
}
一个普通的类,注意getters和setters的写法,定义变量用var,定义函数用function【不多余吗- -|||】,注意与之前学习的语言的不同点。
The access control of a variable determines who can access it. The choices are public (any class), protected (the class itself or subclasses), internal (classes in the same package) or private (the class itself). Unlike in Java, protected does not give access to classes in the same package.
The core classes include Object (everything that isn’t primitive is an Object ), Array , Date , Error (for exceptions), Function (which are called methods when they’re part of objects), RegExp , XML , and XMLList
As we’ll see later in this chapter, ActionScript 3 features outstanding XML support using something called E4X.

SESSION 7  Objects, Arrays, Collections, and Looping

session07/src/Tester.mxml

<?xml version="1.0" encoding="utf-8"?>
<s:Application
  xmlns:fx="http://ns.adobe.com/mxml/2009"
  xmlns:s="library://ns.adobe.com/flex/spark"
  xmlns:mx="library://ns.adobe.com/flex/halo"
  width="100%" height="100%"
  initialize="init()">
<fx:Script>
<![CDATA[
  import mx.collections.ArrayCollection;
  
  private function init():void {
    var foo:Object = new Object();
    var house:Object = {country:"Canada", province:"BC", city:"Vancouver"}; //{key1:value1, ...}
    var ary:Array = [foo, house, 1]; //也可使用new Array()
    ary.push("last"); //加入尾部
    ary.unshift(true); //加入首部
    
    var output:String = "Join:\n" + ary.join(", ") + "\n";
    output += "for loop over Array:\n";
    for (var i:int = 0; i < ary.length; i++) {
      output += ary[i] + (i == ary.length - 1 ? "\n\n" : ", ");
    }
    output += "for loop over ArrayCollection:\n"; 
    var ac:ArrayCollection = new ArrayCollection(ary); //ArrayCollection is more suitable for data binding than  Array   is
    for (var j:int = 0; j < ac.length; j++) { //这里不能用i,因为前面用过了
      output += ac.getItemAt(j);
      switch(j) {
        case ac.length - 1:
          output += "\n";
          break;
        default:
          output += ", ";
          break;
      }
    }
    output += "for each loop over ArrayCollection:\n";
    var k:int = 0;
    for each (var item:Object in ac) { //for each ... in : iterates over the values in a collection
      output += item;
      if (k != ac.length - 1) {
        output += ", "; 
      } else {
        output += "\n\n";
      }
      k++;
    }
    output += "for in over Object properties:\n"
    for (var key:String in house) { //for ... in : iterates over the keys in a collection (or in an Object)
      output += house[key] + ", ";
    }
    outputTA.text = output;
  }
]]>
</fx:Script>
  <s:TextArea id="outputTA" width="100%" height="100%"/>
</s:Application>
variables inside a function are all in the same scope, the for loop does not create its own variable scope.(非典型)

SESSION 8  Interfaces, casting, is, and as

Unfortunately, unlike Java, you can’t add constants to ActionScript 3 interfaces.
you can’t implement an interface and use a public var in the place of the getters and setters, which would have been a nice shortcut in trivial cases.
session08/src/model/IThing.as
package model {
  public interface IThing {
    function get name():String; //不能有public
    function set name(value:String):void;
    function getPoints():int;
  }
}
Note that no access control specifier is needed (or permitted), since all functions in an interface are public .

session08/src/model/Task.as

package model {
  public class Task implements IThing {
    private var _name:String; //私有变量命名的惯例
    public var points:int;
    public var due:Date;
    public static const ONE_DAY_IN_MSEC:Number = 1000*60*60*24;
    
    public function Task(name:String = "") {
      this.name = name;
      due = new Date();
      due.setTime(due.getTime() + ONE_DAY_IN_MSEC); //Date#getTime() method returns a Number, not an int.
    }
    public function getPoints():int {
      return points;
    }
    public function set name(value:String):void {
      _name = value;
    }
    public function get name():String {
      return _name;
    }
  }
}
session08/src/model/Project.as
package model {
  import mx.collections.ArrayCollection;

  public class Project implements IThing {
    private var _name:String;
    public var tasks:ArrayCollection;
  	
    public function Project(name:String = "") {
      this.name = name;
      tasks = new ArrayCollection();
    }
    public function set name(value:String):void {
      _name = value;
    }
    public function get name():String {
      return _name;
    }
    public function getPoints():int {
      var pointsTotal:int = 0;
      for each (var task:Task in tasks) {
        pointsTotal += task.points;
      }
      return pointsTotal;
    }
  }
}
session08/src/Tester.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:Application
  xmlns:fx="http://ns.adobe.com/mxml/2009"
  xmlns:s="library://ns.adobe.com/flex/spark"
  xmlns:mx="library://ns.adobe.com/flex/halo"
  width="100%" height="100%"
  initialize="init()">
<fx:Script>
<![CDATA[
  import mx.collections.ArrayCollection;
  import model.Task;
  import model.Project;  
  import model.IThing;
  
  private function init():void {
    var project1:Project = new Project("project 1");
    var project2:Project = new Project("project 2");
    var task1:Task = new Task("task 1");
    task1.points = 3;
    var task2:Task = new Task("task 2");
    task2.points = 1;
    project1.tasks = new ArrayCollection([task1, task2]);
    var things:ArrayCollection = new ArrayCollection([task1, task2, project2]); //参数为数组
    things.addItemAt(project1, 2); //
    var output:String = "";
    for each (var thing:IThing in things) {
      output += thing.name + " (points: " + thing.getPoints() + ")";
      if (thing is Task) { //is
  	var task:Task = Task(thing); //cast,类型转换,注意语法,不是(Task)thing,- -||||||||||
  	output += ", due: " + task.due;
      }
      var project:Project = thing as Project; //较安全的类型转换,类型不匹配则返回null
      if (project != null) { //null check
  	output += ", " + project.tasks.length + " tasks";
      }
      output += "\n";
    }
    outputTA.text = output;
  }
]]>
</fx:Script>
  <s:TextArea id="outputTA" width="100%" height="100%"/>
</s:Application>
The as operator can be used safely where casting might blow up (if the object was the wrong type). If the type doesn’t match, it just returns null . So, we use a null check.
The is keyword can be used to test whether an object is an instance of a class (which includes a subclass of that class).

SESSION 9  Inheritance

session09/src/model/Thing.as

package model {
  public class Thing implements IThing {
    protected var _name:String;
    public function Thing(name:String = "") {
      this.name = name;
    }
    public function getPoints():int {
      throw new Error("Unimplemented getPoints method"); //Thing throws an Error if getPoints() isn’t overridden. An Error is the ActionScript 3 version of an exception.

    }
    public function set name(value:String):void {
      _name = value;
    }
    public function get name():String {
      return _name;
    }
  }
}
Thing has a protected _name variable. When building something you intend to be subclassed, you can use protected instead of private if you want to allow subclasses to have more access to the internals of the parent class. Or, you can take the approach of making the variable private and providing get/set methods, in order to ensure that subclasses access variables the same way as the outside world.

session09/src/model/Task.as

package model {
  public class Task extends Thing {         
    public var points:int;
    public var due:Date;
    public static const ONE_DAY_IN_MSEC:Number = 1000*60*60*24;
    
    public function Task(name:String = "") {
      super(name);
      due = new Date();
      due.setTime(due.getTime() + ONE_DAY_IN_MSEC);
    }
    public override function getPoints():int {  //必须要有override关键字
      return points;
    }
  }
}

Project类的修改类似

When overriding a function, use the override keyword.

SESSION 10  E4X, XML, XMLList, and XMLListCollections(最重要!)

session10/src/Tester.mxml

<?xml version="1.0" encoding="utf-8"?>
<s:Application
  xmlns:fx="http://ns.adobe.com/mxml/2009"
  xmlns:s="library://ns.adobe.com/flex/spark"
  xmlns:mx="library://ns.adobe.com/flex/halo"
  width="100%" height="100%"
  initialize="init()">
<fx:Script>
<![CDATA[
    import mx.collections.XMLListCollection; //
    import mx.collections.Sort;
    import mx.collections.SortField;
    
  private var _projectsXML:XML = //很神奇
<projects>
  <project id="1" name="Proj1">
    <task id="1">
      <name>Understand E4X</name> //ECMAScript 4 XML
      <notes>cool, for XML anyway</notes>
    </task>
    <task id="2">
      <name>Learn XMLList</name>
      <notes>simple</notes>
    </task>
  </project>
  <project id="2" name="Proj2">
    <task id="3">
      <name>Learn XMLListCollection</name>
    </task>
    <task id="4">
      <name>Get a coffee</name>
      <notes>very necessary</notes>
    </task>
  </project>
</projects>;

  private function init():void {
    var output:String = "";
    output += "Full XML:\n" + _projectsXML;
    output += "\n\nUsing E4X and XMLList:\n";
    output += _projectsXML.project[0].task[0].name + "\n";
    output += _projectsXML.project.(@name=="Proj2").task.(@id==3).name; //注意这里的操作方法
    var projects:XMLList = _projectsXML.children(); //Getting the children of an XML object gets an XMLList, which can be iterated on with a for each loop.

    for each (var project:XML in projects) {
      output += "Project: " + project.@name + "\n"; //
      for each (var task:XML in project.task) {
        output += "  Task " + task.@id + ": " + task.name;
        if (task.hasOwnProperty('notes')) { //
          output += " (" + task.notes + ")";
        }
        output += "\n";
      }
    }
    output += "\nLearning XMLListCollection and Sorting:\n"
    var allTasks:XMLListCollection = new XMLListCollection(_projectsXML.descendants("task")); //
    var sort:Sort = new Sort();
    sort.fields = [new SortField("name",true)]; //第二个参数表示大小写不敏感
    allTasks.sort = sort;
    allTasks.refresh();
    for each (var sortedTask:XML in allTasks) { //
      output += sortedTask.name + "\n";
    }
    outputTA.text = output;
  }
]]>
</fx:Script>
  <s:TextArea id="outputTA" width="100%" height="100%"/>
</s:Application>
E4X, attribute, and child element values can be retrieved with dot(.) syntax. For an attribute value, just add the @ prefix.
E4X检索子元素直接dot,属性加上@前缀
E4X, which stands for ECMAScript for XML, is a great way to handle XML. You’ll never want to touch the DOM or have SAX again.
XML and XMLList are native types in ActionScript 3 and don’t need to be imported.

输出:

Full XML:
<projects>
  <project id="1" name="Proj1">
    <task id="1">
      <name>Understand E4X</name>
      <notes>cool, for XML anyway</notes>
    </task>
    <task id="2">
      <name>Learn XMLList</name>
      <notes>simple</notes>
    </task>
  </project>
  <project id="2" name="Proj2">
    <task id="3">
      <name>Learn XMLListCollection</name>
    </task>
    <task id="4">
      <name>Get a coffee</name>
      <notes>very necessary</notes>
    </task>
  </project>
</projects>

Using E4X and XMLList:
Understand E4X
Learn XMLListCollection
Project: Proj1
  Task 1: Understand E4X (cool, for XML anyway)
  Task 2: Learn XMLList (simple)
Project: Proj2
  Task 3: Learn XMLListCollection
  Task 4: Get a coffee (very necessary)

Learning XMLListCollection and Sorting:
Get a coffee
Learn XMLList
Learn XMLListCollection
Understand E4X

转载于:https://my.oschina.net/zoey1990/blog/86131

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值