【发布时间】:2019-05-24 18:33:32
【问题描述】:
我正在使用带有纯 JavaScript 的 nativescript 核心。但我不认为这是问题所在。我的问题的基础是我试图向全局数组添加一个新对象,当我这样做时,我以前的数据不断被新对象覆盖。
我尝试了一个普通的 array.push({data}) 和 ES6 spread [...array, {data}]。这两种方法最终都用新对象覆盖了数组中的先前数据。
record-page.js
// import statements
// variables
// 'global' array of markers.
var markers = [];
// this function opens a custom modal
function addObsticalTapped(args) {
// close the popup
var page = args.object.page;
var popup = page.getViewById("trailNotesPopup");
isShown = false;
popup.animate({
translate: {
x: 0,
y: 500
},
duration: 300,
curve: enums.AnimationCurve.easeInOut
});
var mainView = args.object;
var context = {};
geolocation
.getCurrentLocation({
desiredAccuracy: Accuracy.high
})
.then(loc => {
curLoc = loc;
});
mainView.showModal(obsticalModal, context, addObsticalIcon, false);
}
exports.addObsticalTapped = addObsticalTapped;
// callback function when the modal is closed
function addObsticalIcon(didConfirm, data) {
if (didConfirm) {
// this is where the problem is, the markers array is being overwritten
// when adding another marker
markers = [...markers, {
type: "obstical",
location: {
lat: curLoc.latitude,
lng: curLoc.longitude
},
data: data,
trail_id: ""
}];
map.addMarkers([{
id: markerID,
lat: curLoc.latitude,
lng: curLoc.longitude,
//icon: "res://obstical_icon"
iconPath: "./icons/obstical_icon_marker.png"
}]);
markerID++;
console.log(JSON.stringify(markers));
} else {
console.log("closed");
}
}
obstical-modal.js
function onShownModally(args) {
const context = args.context;
closeCallback = args.closeCallback;
const page = args.object;
vm = observableModule.fromObject(context);
vm.set("oneSelected", oneSelected ? oneOn : oneOff);
vm.set("threeSelected", threeSelected ? threeOn : threeOff);
vm.set("sixSelected", sixSelected ? sixOn : sixOff);
vm.set("nineSelected", nineSelected ? nineOn : nineOff);
page.bindingContext = vm;
}
exports.onShownModally = onShownModally;
function onCancel(args) {
closeCallback(false, {});
}
exports.onCancel = onCancel;
function onSubmit(args) {
var page = args.object.page;
var textField = page.getViewById("info");
data.info = textField.text;
closeCallback(true, data);
}
exports.onSubmit = onSubmit;
我期望发生的事情: 障碍一的难度为1,信息为“hello world” 然后将其添加到数组中,数组是正确的。 然后我添加了另一个难度为 3 的障碍和“你好代码”的信息 当它被添加到数组中时,数组看起来像:
[{"type":"obstical","data":{"difficulty":3,"info":"hello code"}},{"type":"obstical","data":{"difficulty":3,"info":"hello code"}}]
【问题讨论】:
标签: javascript node.js nativescript