【发布时间】:2020-10-12 06:49:25
【问题描述】:
我正在使用带有纯 JavaScript 的 NativeScript 7,并且我正在尝试在 ES2017 中编写视图模型代码。
通过 ES2017,我的意思是我正在使用在 ES2017 或之前发布的功能,例如 import/export 和 class 语法。
代码运行成功但数据未绑定。这是代码。
查看模型
import { fromObject } from "@nativescript/core";
export class MainViewModel extends fromObject {
constructor() {
super();
this.counter = 69;
this.message = "meow";
}
getMessage(counter) {
if (counter <= 0)
return "Hoorraaay! You unlocked the NativeScript clicker achievement!";
else
return `${counter} taps left`;
}
onTap() {
console.log("Tapped");
this.message = this.getMessage(this.counter);
this.counter--;
console.log(this.counter);
}
}
主页
import { MainViewModel } from "./main-view-model";
exports.onNavigatingTo = function(args) {
console.log("OnNavigatingTo is called");
const page = args.object;
page.bindingContext = new MainViewModel();
};
主页 XML
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="onNavigatingTo">
<ActionBar title="My App" icon=""></ActionBar>
<StackLayout class="p-20">
<Label text="Tap the button" class="h1 text-center"/>
<Button text="TAP" tap="{{ onTap }}" class="-primary"/>
<Label text="{{ message }}" class="h2 text-center" textWrap="true"/>
</StackLayout>
</Page>
鉴于 NativeScript 7 运行 ES2017,为什么这段代码不起作用(数据被绑定)? 我错过了什么?
另外,请注意,console.log 目前没有显示任何内容。
编辑
为了澄清我所说的“数据被绑定”是什么意思,我的意思是“消息”属性和“onTap()”函数都没有按预期绑定到视图。
更多编辑 - 工作 ES5 代码
视图模型
const fromObject = require("@nativescript/core").fromObject;
exports.MainViewModel = fromObject({
counter: 69,
message: "meow",
getMessage: function(counter) {
if (counter <= 0)
return "Hoorraaay! You unlocked the NativeScript clicker achievement!";
else
return `${counter} taps left`;
},
onTap: function() {
console.log("Tapped");
this.message = this.getMessage(this.counter);
this.counter--;
console.log(this.counter);
}
});
主页
const MainViewModel = require("./main-view-model").MainViewModel;
exports.onNavigatingTo = function(args) {
console.log("OnNavigatingTo is called");
const page = args.object;
page.bindingContext = MainViewModel;
};
主页 XML(相同)
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="onNavigatingTo">
<ActionBar title="My App" icon=""></ActionBar>
<StackLayout class="p-20">
<Label text="Tap the button" class="h1 text-center"/>
<Button text="TAP" tap="{{ onTap }}" class="-primary"/>
<Label text="{{ message }}" class="h2 text-center" textWrap="true"/>
</StackLayout>
</Page>
工作 ES5 代码的屏幕截图
【问题讨论】:
-
import/export和class语法是 ES6 又名 ES2015。 -
没错。鉴于支持 NativeScript 7 的 V8 引擎运行 ES2017(显然是在 ES2015 之后),之前的代码应该可以工作,不是吗?
-
“数据被绑定”是什么意思?究竟是什么错误?
-
@Bergi 请查看我对问题的修改。
-
好的,所以这似乎是一个 nativescript 问题。还是特别是 ES6 问题,即您能否让 ES5 版本的代码工作?
标签: javascript ecmascript-6 nativescript