17.8.记住用户输入文本框的内容

17.8.1. 问题
我想要再用户离开应用程序的时候,记住用户输入的TextInput 的字段。
17.8.2. 解决办法
创建一个TextInput 组建的子类,当用户输入的时候来使用本地共享对象存贮用户输入的文本值。
17.8.3. 讨论
为了方便,现代浏览器都提供了记住用户上次在公共表单区域输入值和登陆提示,这些值在用户再次访问的时候不用再次输入。默认情况,Flex 应用程序没有继承这个非常有用的行为,但是你可以很简单的通过使用本章的例子中的自定义组件来实现。

这个组件继承于TextInput 类,增加了一个静态方法到TextInput 的API,被设计了用来记住最后一次的值. persistenceId 属性是存贮ID 用来指定这个组件的实例。静态方法clearStoredValues()让你可以全局晴空所有之前存贮的值。代码如下:
+展开
-ActionScript
package custom
{
import flash.events.Event;
import flash.net.SharedObject;
import mx.controls.TextInput;
public class PersistentTextInput extends TextInput
{
/**
* The ID this component will use to save and later look up its
* associated value.
*/

public var persistenceId:String = null;
/**
* The SharedObject name to use for storing values.
*/

private static const LOCAL_STORAGE_NAME:String =
"persistentTextInputStorage";
/**
* Clears previously stored values for all PersistentTextInput instances.
*/

public static function clearStoredValues() :void
{
var so:SharedObject = SharedObject.getLocal(LOCAL_STORAGE_NAME);
so.clear();
}
/**
* Handles initialization of this component.
*/

override public function initialize() :void
{
super.initialize();
addEventListener(Event.CHANGE, handleChange);
restoreSavedValue();
}
/**
* Event handler function for CHANGE events from this instance.
*/

protected function handleChange(event:Event) :void
{
saveCurrentValue();
}
/**
* Restores the previously saved value associated with the
* persistenceID of with this instance.
*/

protected function restoreSavedValue() :void
{
if (persistenceId != null)
{
var so:SharedObject =
SharedObject.getLocal(LOCAL_STORAGE_NAME);
var value:String = so.data[persistenceId];
if (value != null)
{
text = value;
}
}
}
/**
* Saves the text value of this instance. Associates the value with
* the persistenceId of this instance.
*/

protected function saveCurrentValue() :void
{
if (persistenceId != null)
{
var so:SharedObject =
SharedObject.getLocal(LOCAL_STORAGE_NAME);
so.data[persistenceId] = text;
so.flush();
}
}
}
}

如下应用程序示范了如何使用这个新组件。测试这些功能,载入应用程序,输入一些文字,然后关闭应用程序。当你再次打开应用程序的时候,你会看到之前输入的一些字段会有之前你输入的值。
+展开
-XML
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxmlxmlns:custom="custom.*layout="vertical">
<mx:Script>
<![CDATA[
import custom.PersistentTextInput;
public function clearValues() :void
{
PersistentTextInput.clearStoredValues();
message.text = "A page refresh will reveal that the
values have not persisted.";
}

]]>
</mx:Script>
<custom:PersistentTextInput id="firstNameInput"
persistenceId="firstName" />

<custom:PersistentTextInput id="lastNameInput"
persistenceId="lastName" />

<mx:Button label="Clear Persistent Values"
click="clearValues()" />

<mx:Label id="message" />
</mx:Application>

加支付宝好友偷能量挖...


评论(0)网络
阅读(125)喜欢(0)flash/flex/fcs/AIR