5.NativeScript Data Binding

Data Binding

Overview

Data binding is the process ofconnecting application user interface (UI) to a data object (business model).With a correct data binding settings and if data object provides propernotifications then when data changes application UI will reflect changesaccordingly (source to target). Depending on settings and requirements there isa possibility to update data from UI to data object (target to source).

source is used as any business logic object, and target asany UI control (like TextField).

Basic data binding concepts

Generally almost every UI control(since all controls are created with data binding in mind) could be bound to adata object. However there are few restrictions for data binding to work out ofthe box.

  • Target object should be a successor of Bindable class.
  • Target property should be a dependency property in order to use data binding from target to source (or two way data binding). A plain property could be used if there is no need of twoWay binding.
  • Data (business) object should raise propertyChange event for every change in the value of the property.

Direction of data flow

Part of the data binding settings isthe way data (values) flows. NativeScript data binding supports following datatransmissions.

  • OneWay - this is a setting that indicates that a change in the source object will update target property, but a change in target property will not be propagated back to source (data object). Any update to the target property (except binding) will stop the binding connection. - this is the default option.
  • TwoWay - this setting indicates that both changes in source object will be reflected to the target and changes from target will update the source object. Very useful in cases when user input should be handled (for example user writes a text - text is written within a TextField control and is updated to a underlying data property of the source object). In order to use this option binding options should set twoWay as true. Following examples show how to do that.

Creating a binding

  • Creating binding in code.

In order to create a working bindingfirst we should have a source object. Source object should raise propertyChangeevent for every change of any property. NativeScript has a built-inclass that fulfills that requirement (Observable). Following is acode snippet that creates an observable object instance.

  • JavaScript
  • TypeScript

varobservableModule = require("data/observable");

varsource = new observableModule.Observable();

Creating a target object. For thesake of example we will also create a target object an instance of Bindableclass (all UI controls derives from it).

  • JavaScript
  • TypeScript

vartextFieldModule = require("ui/text-field");

vartargetTextField = new textFieldModule.TextField();

Create a data binding.

  • JavaScript
  • TypeScript

varbindingOptions = {

    sourceProperty: "textSource",

    targetProperty: "text",

    twoWay: true

};

targetTextField.bind(bindingOptions,source);

source.set("textSource","Text set via binding");

This example will update targetTextField.textproperty with a "Text set via binding" value, twoWayoption ensures that every change of the targetTextField.text property(via user input) will be stored within source.text property. The newvalue of the text property could be get via:

  • JavaScript
  • TypeScript

source.get("textSource");

  • Create a data binding in xml
    1. Create a source object. "source" object from the previous case (creating binding with code) will be used for following examples.
    2. Describe a binding within xml (using a mustache syntax).
  • XML

<Page>

    <StackLayout>

        <TextField text= {{ textSource }}/>

        </StackLayout>

</Page>

Note: For an UI elements createdwith an xml declaration when data binding is set twoWay option is trueby default.

With an xml declaration we set onlyproperties names both for target (text) and source (textSource). Theinteresting thing here is that there is no source of the binding (actually itis not set directly).

Binding source

The important part of the databinding is setting the source object. NativeScript data binding works with anyobject that emits a propertyChange event. On the process of creatingbinding source can be set as second parameter of the bind(bindingOptions,source) or could be omitted. In that case for source is used a special propertynamed bindingContext of the Bindable class. The special about thisproperty is that it is inheritable across the visual tree. This means thatcontrol can use the bindingContext (as source) of the first parentelement with a explicitly set bindingContext. With the previous example bindingContextcan be set either on Page instance or StackLayout instance and TextField willhave a proper source for its "text" property binding.

  • JavaScript
  • TypeScript

page.bindingContext= source;

//or

stackLayout.bindingContext= source;

  • Create a data binding to an event in xml

There is an option to bind afunction to execute on a specific event (MVVM command like). This option isavailable only through an xml declaration. The different part is that thesource property should have an event handler function as value.

  • JavaScript
  • TypeScript

page.bindingContext= source;

source.set("onTap",function(eventData) {

        console.log("button istapped!");

});

and how xml will look like:

  • XML

<Page>

    <StackLayout>

        <Button text="Test Button ForBinding" tap="{{ onTap }}" />

    </StackLayout>

</Page>

Note: Be aware that if there is anevent handler function onTap within the page code behind (more info about xml declarations),and onTap function within the bindingContext object then therewill be 2 event handlers hooked for that button and both will be executed ontap event.

Stop binding

Generally there is no need to stopbinding explicitly, since Binding object uses weak references which preventsany memory leaks. However there are some scenarios (business logic) wherebinding must be stopped. In order to stop existing data binding just call unbindmethod with target property name as argument.

  • JavaScript
  • TypeScript

targetTextField.unbind("text");

More information about binding canbe found in API-Ref.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章