Nativescript SegmentedBar propertyChangeEvent

Nativescript SegmentedBar propertyChangeEvent

我在 Nativescript 中创建了一个 segmentedbar,但我创建的 propertyChangeEvent 侦听器没有接收到我的更改。谁能告诉我我的错误是什么?

XML

代码
<SegmentedBar row="1" colspan="3" class="toggles" selectedBackgroundColor="#B76769" selectedIndex="{{ bookingsObsSelectedIndex }}">
      <SegmentedBar.items>
            <SegmentedBarItem title="Product"/>
            <SegmentedBarItem title="Service" completed="false"/>
            <SegmentedBarItem title="Total" completed="true"/>
      </SegmentedBar.items>
</SegmentedBar>

将我的索引绑定到可观察对象并创建一个 propertychange 事件。

var observableModule = require("data/observable");
var bookingsObsSelectedIndex = new observableModule.Observable();

bookingsObsSelectedIndex.on(observableModule.Observable.propertyChangeEvent, function (propertyChangeData) {
    console.log("Property changed for bookingsObs, changed property name: = "+propertyChangeData.propertyName);
});

抱歉,我是 Nativescript 的新手。正在尝试按照指定的步骤进行操作 here.

您应该使用 addEventListener 方法而不是 on 来处理 属性 更改事件。您的代码应该是这样的:

主-page.xml

<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo">
  <StackLayout>
  <SegmentedBar  selectedIndex="{{ bookingsObsSelectedIndex }}">
      <SegmentedBar.items>
            <SegmentedBarItem title="Product"/>
            <SegmentedBarItem title="Service" completed="false"/>
            <SegmentedBarItem title="Total" completed="true"/>
      </SegmentedBar.items>
  </SegmentedBar>

  </StackLayout>
</Page>

主-page.js

var observable_1 = require("data/observable"); // Event handler for Page "navigatingTo" event attached in main-page.xml function navigatingTo(args) {
    // Get the event sender
    var page = args.object;
    var newObservable = new observable_1.Observable();
    newObservable.set("bookingsObsSelectedIndex", 1);
    newObservable.addEventListener(observable_1.Observable.propertyChangeEvent, function (pcd) {
        console.log(pcd.eventName.toString() + " " + pcd.propertyName.toString() + " " + pcd.value.toString());
    });
    page.bindingContext = newObservable; } exports.navigatingTo = navigatingTo;

关于这一点,您可以阅读有关绑定的更多信息 here

您正在阅读的 SO 答案有点旧,此后 selectedIndexChanged 事件被添加到 SegmentedBar。因此,您可以直接挂钩到新事件,而不是使用绑定可观察对象的 propertyChanged 事件:

    <SegmentedBar row="1" colspan="3" class="toggles" selectedBackgroundColor="#B76769" 
selectedIndex="{{ bookingsObsSelectedIndex }}" selectedIndexChanged="segmentedBarIndexChanged">
          <SegmentedBar.items>
                <SegmentedBarItem title="Product"/>
                <SegmentedBarItem title="Service" completed="false"/>
                <SegmentedBarItem title="Total" completed="true"/>
          </SegmentedBar.items>
    </SegmentedBar>

然后在您的页面 javascript 中添加类似内容:

function segmentedBarIndexChanged(args) {
    console.log("Tab selected: " + args.newIndex + ", old one is:" + args.oldIndex);
}
exports.segmentedBarIndexChanged = segmentedBarIndexChanged;