据我所知,NativeScript 中没有 blur(-like) 事件。但是,您可以在文本更改时做出反应。
您要做的是利用NativeScript 中的数据绑定机制和
可观察对象。
简而言之,数据绑定将允许您将用户界面(通常在您的 XML 文件中描述)与您的业务模型/数据对象连接起来。数据绑定可以是“一种方式”,这意味着您在数据对象中所做的任何更改都将反映在 UI 中。它也可以是两种方式,这意味着您在 UI 中所做的任何更改也将反映在您的数据对象中。
在您的情况下,您需要两种方式绑定,因为您希望 UI(用户输入文本)中发生的任何事情都反映在您的模型中。
例子
xml
假设你有这个 xml:
<Page xmlns="http://www.nativescript.org/tns.xsd" loaded="pageLoaded">
<StackLayout>
<TextField text="{{ description }}" />
</StackLayout>
</Page>
js
为了更容易理解,我已经注释了内联。
var observable = require("data/observable");
function pageLoaded(args) {
var page = args.object;
/**
* Creating a new Observable object.
*/
var contextObj = new observable.Observable();
/**
* Setting the property 'description' to 'hi there'.
* In your XML you'll attach this property to the
* Text field as such:
* <TextField text="{{ description }}" />
* This means that the Text field will, by default
* be prepopulated with 'Hi there'
*/
contextObj.set("description", "Hi there");
/**
* Attaching the observable object to the
* 'bindingContext' of the page. This is a
* special property to which you want to attach
* the object. By default bindings are two way.
*/
page.bindingContext = contextObj;
/**
* Event listener.
* When the user is changing the text in the UI, this gets propagated down
* to the contextObj which will change. Here we add an event listener for
* changes and log some information about the change that just happened.
*/
contextObj.addEventListener(observable.Observable.propertyChangeEvent, function (event) {
console.log('The object changed!');
console.log('Event: ' + event.eventName);
console.log('propertyName: ' + event.propertyName);
console.log('New value: ' + event.value);
console.log('');
});
}
exports.pageLoaded = pageLoaded;