Coffeescript is treating finally() method of promise as a property - coffeescript

The coffescript is messing up the .finall() method of the promise and making it })["finally"](function() { instead of calling it as a method of the promise object.
angular.module("main.loadbalancer")
.controller "CreateNodeCtrl", ($scope, $modalInstance,
LoadBalancerService, StatusTrackerService, NodeService) ->
$scope.createNode = (node) ->
$scope.disableButtonsForRun = false
$scope.statusBar = true
$scope.nodeStatus = "Building"
$scope.statusType = "warning"
LoadBalancerService.getLoadBalancer().then (loadBalancer) ->
NodeService.createNode(
account_number: foo
admin_state: "enabled"
label: node.label
ip: node.ip
port: node.port
comment: node.comment
health_strategy: {}
vendor_extensions: {}
).then((eventId) ->
$scope.disableButtonsForRun = true
trackStatus = StatusTrackerService.runEventCheck "9936", "0fd6afd9-4aa0-a5c9-ff0b3e60cdcf"
trackStatus.then (( ->
$scope.statusType = "success"
$scope.nodeStatus = "Completed Successfully"
setTimeout ( ->
$modalInstance.close()
return
), 3000
), ( ->
$scope.nodeStatus = "Failure!"
$scope.statusType = "danger"
))
.finally ->
$scope.disableButtonsForRun = false
TypeError: Object function () {
$scope.nodeStatus = "Failure!";
return $scope.statusType = "danger";
} has no method 'finally'
angular.module("main.loadbalancer").controller("CreateNodeCtrl", function($scope, $modalInstance, LoadBalancerService, StatusTrackerService, NodeService) {
$scope.createNode = function(node) {
$scope.disableButtonsForRun = false;
$scope.statusBar = true;
$scope.nodeStatus = "Building";
$scope.statusType = "warning";
return LoadBalancerService.getLoadBalancer().then(function(loadBalancer) {
$scope.statusBar = true;
return NodeService.createNode({
account_number: loadBalancer.customer,
admin_state: "enabled",
label: node.label,
ip: node.ip,
port: node.port,
comment: node.comment,
health_strategy: {},
vendor_extensions: {}
}).then(function(eventId) {
$scope.disableButtonsForRun = true;
return StatusTrackerService.runEventCheck("9936", "0fd6afd9-7-4aa0-a5c9-ff0b3e60cdcf");
}).then((function() {
$scope.statusType = "success";
return $scope.nodeStatus = "Completed Successfully";
setTimeout((function() {
$modalInstance.close();
}), 3000);
}), (function() {
$scope.nodeStatus = "Failure!";
return $scope.statusType = "danger";
})["finally"](function() {
return $scope.disableButtonsForRun = false;
}));
});
};

You have 13 opening braces and only 12 closing.
Maybe an extra ( here:
trackStatus.then ((
# ^
$scope.statusType = "success"
$scope.nodeStatus = "Completed Successfully"

Your posted indentation isn't consistent. The last line, Line 34: $scope.disableButtonsForRun = false, has an extra level of indention.
Try this:
angular.module("main.loadbalancer")
.controller "CreateNodeCtrl", ($scope, $modalInstance,
LoadBalancerService, StatusTrackerService, NodeService) ->
$scope.createNode = (node) ->
$scope.disableButtonsForRun = false
$scope.statusBar = true
$scope.nodeStatus = "Building"
$scope.statusType = "warning"
LoadBalancerService.getLoadBalancer().then (loadBalancer) ->
NodeService.createNode(
account_number: foo
admin_state: "enabled"
label: node.label
ip: node.ip
port: node.port
comment: node.comment
health_strategy: {}
vendor_extensions: {}
).then((eventId) ->
$scope.disableButtonsForRun = true
trackStatus = StatusTrackerService.runEventCheck "9936", "0fd6afd9-4aa0-a5c9-ff0b3e60cdcf"
trackStatus.then (( ->
$scope.statusType = "success"
$scope.nodeStatus = "Completed Successfully"
setTimeout ( ->
$modalInstance.close()
return
), 3000
), ( ->
$scope.nodeStatus = "Failure!"
$scope.statusType = "danger"
))
.finally ->
$scope.disableButtonsForRun = false

Related

Flow invariant is violated

Resources:::
ViewModel -->
#ExperimentalCoroutinesApi
#HiltViewModel
class TestimonialViewModel
#Inject constructor(
private val testimonialRepo: TestimonialRepo,
private val authRepo: AuthRepo,
val networkHelper: NetworkHelper,
private val savedStateHandle: SavedStateHandle,
) : ViewModel() {
var title by mutableStateOf(UiString.Resource(R.string.testimonial_title_create))
private set
var data by mutableStateOf(TestimonialData())
private set
private var curInx = 0
private val _areInputsValid = MutableStateFlow(false)
val areInputsValid = _areInputsValid.asStateFlow()
private val _mutableState = MutableStateFlow<TestimonialGetState>(TestimonialGetState.Loading)
val state = _mutableState.asStateFlow()
private val _stateChannel = Channel<TestimonialSubmitState>()
val stateChannel = _stateChannel.receiveAsFlow()
init {
onLoad()
}
fun onLoad() {
if (networkHelper.isConnected()) {
authRepo.getUser()?.let {
loadTestimonial(userId = it.uid)
}
} else {
_mutableState.value = TestimonialGetState.NoInternet
}
}
private fun loadTestimonial(userId: String) {
viewModelScope.launch {
testimonialRepo.getTestimonial(userId).catch { ex ->
//_mutableState.value = TestimonialGetState.Error(ex)
_mutableState.value = TestimonialGetState.Empty
}.collect {
if (it.id.isNotBlank())
title = UiString.Resource(R.string.testimonial_title_edit)
data = TestimonialData(
id = it.id,
type = it.type,
title = it.title,
testimonial = it.testimonial,
role = it.user.role,
org = it.user.org
)
when (it.type) {
TestimonialType.TEXT -> {
}
TestimonialType.IMAGE -> {
data.imgMedia = it.media.toMutableStateList()
}
TestimonialType.VIDEO -> {
data.vdoMedia = it.media.toMutableStateList()
}
}
_mutableState.value = TestimonialGetState.Success(it)
}
}
}
private fun updateTestimonial(netTestimonial: Testimonial) {
viewModelScope.launch {
testimonialRepo.updateTestimonial(netTestimonial)
.catch { ex ->
_stateChannel.send(TestimonialSubmitState.Error(ex))
}.collect {
clearErrors()
_stateChannel.send(TestimonialSubmitState.Success(it))
}
}
}
fun onEvent(event: TestimonialEvent) {
when (event) {
is TestimonialEvent.OnTypeChange -> {
data = data.copy(type = event.type)
_areInputsValid.value = validateTestimonial(event.type)
}
is TestimonialEvent.OnTitleChange -> {
data = data.copy(title = event.title)
data.titleError = onValidateText(event.title, 4, 64)
_areInputsValid.value = validateTestimonial(data.type)
}
is TestimonialEvent.OnTestimonialChange -> {
data = data.copy(testimonial = event.testimonial)
data.testimonialError = onValidateText(event.testimonial, 32, 256)
_areInputsValid.value = validateTestimonial(data.type)
}
is TestimonialEvent.OnOrgChange -> {
data = data.copy(org = event.org)
data.orgError = onValidateText(event.org, 4, 32)
_areInputsValid.value = validateTestimonial(data.type)
}
is TestimonialEvent.OnRoleChange -> {
data = data.copy(role = event.role)
data.roleError = onValidateText(event.role, 2, 32)
_areInputsValid.value = validateTestimonial(data.type)
}
is TestimonialEvent.OnMediaIndex -> {
curInx = event.inx
}
is TestimonialEvent.OnImageSelect -> {
if (event.url != null) {
data.imgMedia[curInx] = data.imgMedia[curInx].copy(localUrl = event.url)
}
data.imgError = onValidateMedia(data.imgMedia)
_areInputsValid.value = validateTestimonial(data.type)
}
is TestimonialEvent.OnImageClear -> {
data.imgMedia[event.inx] = data.imgMedia[event.inx].copy(localUrl = null, url = "")
data.imgError = UiString.Resource(R.string.the_media_can_not_be_blank)
_areInputsValid.value = validateTestimonial(data.type)
}
is TestimonialEvent.OnVideoSelect -> {
if (event.url != null) {
data.vdoMedia[curInx] = data.vdoMedia[curInx].copy(localUrl = event.url)
}
data.vdoError = onValidateMedia(data.vdoMedia)
_areInputsValid.value = validateTestimonial(data.type)
}
is TestimonialEvent.OnVideoClear -> {
data.vdoMedia[event.inx] = data.vdoMedia[event.inx].copy(localUrl = null, url = "")
data.vdoError = UiString.Resource(R.string.the_media_can_not_be_blank)
_areInputsValid.value = validateTestimonial(data.type)
}
is TestimonialEvent.OnSubmit -> {
submit()
}
}
}
private fun submit() {
authRepo.getUser()?.let {
updateTestimonial(
Testimonial(
id = data.id,
type = data.type,
title = data.title.trim(),
testimonial = data.testimonial.trim(),
userId = it.uid,
user = TestimonialUser(
name = it.name!!,
role = data.role.trim(),
org = data.org.trim(),
url = it.photoUrl.toString()
),
media = when (data.type) {
TestimonialType.TEXT -> listOf()
TestimonialType.IMAGE -> data.imgMedia
TestimonialType.VIDEO -> data.vdoMedia
}
)
)
}
}
private fun clearErrors() {
data.titleError = UiString.Empty
data.testimonialError = UiString.Empty
data.roleError = UiString.Empty
data.orgError = UiString.Empty
data.imgError = UiString.Empty
data.vdoError = UiString.Empty
}
private fun onValidateText(value: String, min: Int, max: Int): UiString {
return when {
value.isBlank() -> UiString.Resource(R.string.the_field_can_not_be_blank)
value.length > max -> UiString.Resource(R.string.data_length_more, max)
value.length in 1 until min -> UiString.Resource(R.string.data_length_less, min)
else -> UiString.Empty
}
}
private fun onValidateMedia(mediaList: List<Media>): UiString {
return if (validateMedia(mediaList)) UiString.Empty
else UiString.Resource(R.string.the_media_can_not_be_blank)
}
private fun validateMedia(mediaList: List<Media>): Boolean {
return mediaList.find { it.localUrl == null && it.url.isBlank() } == null
}
private fun validateTestimonial(type: TestimonialType): Boolean {
return when (type) {
TestimonialType.TEXT -> validateData(
data.testimonial.isNotBlank() && data.testimonialError is UiString.Empty
)
TestimonialType.IMAGE -> validateData(
validateMedia(data.imgMedia) && data.imgError is UiString.Empty
)
TestimonialType.VIDEO -> validateData(
validateMedia(data.vdoMedia) && data.vdoError is UiString.Empty
)
}
}
private fun validateData(typeValidation: Boolean): Boolean {
return (typeValidation && data.title.isNotBlank() && data.titleError is UiString.Empty
&& data.org.isNotBlank() && data.orgError is UiString.Empty
&& data.role.isNotBlank() && data.roleError is UiString.Empty
)
}
}
TestimonialsSubmitState ->
sealed class TestimonialSubmitState {
object Loading : TestimonialSubmitState()
class Error(val error: Throwable) : TestimonialSubmitState()
class Success(val status: Status) : TestimonialSubmitState()
}
UI Component ->
#OptIn(ExperimentalCoroutinesApi::class)
#Composable
fun TestimonialForm(
editViewModel: TestimonialViewModel = hiltViewModel(),
paddingValues: PaddingValues,
onNavigateTstHome: () -> Unit,
) {
val focusRequester = remember { FocusRequester() }
val radioButtonList = listOf(
TestimonialType.TEXT, TestimonialType.IMAGE, TestimonialType.VIDEO
)
var showCustomDialogWithResult by remember { mutableStateOf(false) }
val selectedOption = radioButtonList.find {
it == editViewModel.data.type
} ?: radioButtonList[0]
val focusManager = LocalFocusManager.current
val scrollState = rememberScrollState()
val areInputsValid by editViewModel.areInputsValid.collectAsStateWithLifecycle()
val events = editViewModel.stateChannel.collectAsState(initial = TestimonialSubmitState.Loading)
val event = events.value
Column(
modifier = Modifier
.fillMaxWidth()
.padding(
top = paddingValues.calculateTopPadding(),
start = spacing.medium,
end = spacing.medium
)
.verticalScroll(scrollState), verticalArrangement = Arrangement.Center
) {
Spacer(modifier = Modifier.height(spacing.medium))
TestimonialsRadioButton(selectionTypeText = "Testimonial Type",
radioButtonList = radioButtonList,
selectedOption = selectedOption,
content = {
ValidatedTextField(
value = editViewModel.data.testimonial,
onValueChange = {
editViewModel.onEvent(
TestimonialEvent.OnTestimonialChange(
it
)
)
},
label = "Testimonial",
showError = editViewModel.data.testimonialError !is UiString.Empty,
errorMessage = editViewModel.data.testimonialError,
keyboardOptions = if (editViewModel.data.testimonial.length < 512) {
KeyboardOptions(
keyboardType = KeyboardType.Text, imeAction = ImeAction.Default
)
} else {
KeyboardOptions(
keyboardType = KeyboardType.Text, imeAction = ImeAction.Next
)
},
keyboardActions = KeyboardActions(onNext = {
focusManager.clearFocus()
}),
modifier = Modifier.height(boxSize.extraMedium)
)
},
titleTestimonial = {
ValidatedTextField(
value = editViewModel.data.title,
onValueChange = { editViewModel.onEvent(TestimonialEvent.OnTitleChange(it)) },
label = "Title",
showError = editViewModel.data.titleError !is UiString.Empty,
errorMessage = editViewModel.data.titleError,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text, imeAction = ImeAction.Next
),
keyboardActions = KeyboardActions(onNext = {
focusManager.moveFocus(FocusDirection.Down)
})
)
},
onOptionSelected = {
editViewModel.onEvent(TestimonialEvent.OnTypeChange(it))
})
Spacer(modifier = Modifier.height(spacing.medium))
ValidatedTextField(
value = editViewModel.data.org,
onValueChange = { editViewModel.onEvent(TestimonialEvent.OnOrgChange(it)) },
label = "Organisation",
showError = editViewModel.data.orgError !is UiString.Empty,
errorMessage = editViewModel.data.orgError,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text, imeAction = ImeAction.Next
),
keyboardActions = KeyboardActions(onNext = {
focusManager.moveFocus(FocusDirection.Down)
})
)
Spacer(modifier = Modifier.height(spacing.medium))
ValidatedTextField(
value = editViewModel.data.role,
onValueChange = { editViewModel.onEvent(TestimonialEvent.OnRoleChange(it)) },
label = "Role",
showError = editViewModel.data.roleError !is UiString.Empty,
errorMessage = editViewModel.data.roleError,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text, imeAction = ImeAction.Done
),
modifier = Modifier.focusRequester(focusRequester = focusRequester),
keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() })
)
if (selectedOption == radioButtonList[1]) {
Spacer(modifier = Modifier.height(spacing.medium))
TestGetImage()
} else if (selectedOption == radioButtonList[2]) {
Spacer(modifier = Modifier.height(spacing.medium))
TestGetVideo()
}
androidx.compose.material.Button(
onClick = {
editViewModel.onEvent(TestimonialEvent.OnSubmit)
showCustomDialogWithResult = !showCustomDialogWithResult
},
modifier = Modifier
.fillMaxWidth(1f)
.padding(spacing.medium),
colors = ButtonDefaults.buttonColors(
backgroundColor = Color.Blue, contentColor = Color.White
),
enabled = areInputsValid
) {
Text(text = "Submit", style = MaterialTheme.typography.labelLarge)
}
if (showCustomDialogWithResult) {
when (event) {
is TestimonialSubmitState.Error -> {
Log.d("validate", "Error -> ${event.error.message} and ${event.error.cause}")
}
TestimonialSubmitState.Loading -> {
LoadingAnimation()
}
is TestimonialSubmitState.Success -> {
OnSuccessfulSubmit(onDismiss = {
showCustomDialogWithResult = !showCustomDialogWithResult
}, onNavigateTstHome = onNavigateTstHome, onPositiveClick = {
editViewModel.onEvent(TestimonialEvent.OnSubmit)
onNavigateTstHome()
})
}
}
}
}
}
SuccessfulSubmit Dialog ->
Here, LaunchedEffect block is just for testing purpose.
#Composable
fun OnSuccessfulSubmit(
onDismiss: () -> Unit,
onNavigateTstHome: () -> Unit,
onPositiveClick: () -> Unit,
) {
var underReview by remember {
mutableStateOf(true)
}
LaunchedEffect(key1 = Unit, block = {
delay(2000)
underReview = false
delay(3000)
onNavigateTstHome()
})
Dialog(
onDismissRequest = onDismiss, properties = DialogProperties(dismissOnClickOutside = false)
) {
SuccessfulCard(onClick = onPositiveClick, underReview = underReview)
}
}
Error --->
When I click on Submit Button --->
Log --->
Question -->
What is this error in Log... Code part related to it --->
_stateChannel, stateChannel, updateTestimonial(), submit() ---> inherited in Testimonial form ----> last 2nd Button Component and below it event calling is DONE.
Sorry for bad structuring of the question.
Thank you.
Things I tried ---> events variable in TestimonialForm, I tried to make collectAsState( initial = null )
Also tried LaunchedEffect for when case as suggested in other similar question on Stackoverflow, but got Composable invocation error.

AgGrid tree grid does not show identical leaf name items on the same group level

I'm using AgGrid with tree data. https://www.ag-grid.com/javascript-grid-tree-data/
The problem is that I need to have 2 leaf node on the tree with the same name, because they share the name but not it's properties.
I thought this was specified by getRowNodeId GridOption. Example of usage in Option 1: https://www.ag-grid.com/javascript-grid-rxjs/.
But it doesn't.
He is my code of that property:
...
getRowNodeId: (data: any) => any = (data) => {
return (data.parent !== undefined ? data.parent * 1000 : 0) + data.properties.id;
},
...
As you can see, I want to add 2 nodes with the same name but only 1 renders. What can I do?
UPDATE: Code added
My AgGrid component:
import { Component, ViewChild, ElementRef, OnDestroy, Input, Output, EventEmitter } from '#angular/core';
import { Events, ToastController, AlertController } from 'ionic-angular';
import * as _ from 'lodash';
import 'ag-grid-enterprise';
import { Http } from '#angular/http';
import { GridApi, TemplateService, GridOptions, ColDef } from 'ag-grid';
import { TemplateServiceProvider } from '../../providers/services';
import { NgModel } from '#angular/forms';
import { Toast } from '../../classes/classes';
import { EventSubscriber } from '../../classes/eventSubscriber/eventSubscriber';
#Component({
selector: 'page-datatableWithGroups',
templateUrl: 'datatableWithGroups.html'
})
export class DatatableWithGroupsPage extends EventSubscriber implements OnDestroy {
#ViewChild('quickFilterInput') quickFilterInput: ElementRef;
#Input() rowData: any[] = [];
#Input() columnDefs = [];
#Input() title: string;
#Output() onLoadRow: EventEmitter<any> = new EventEmitter();
#Output() onAddRow: EventEmitter<any> = new EventEmitter();
#Output() onDeleteRow: EventEmitter<any> = new EventEmitter();
#Output() onDuplicateRow: EventEmitter<any> = new EventEmitter();
#Output() onSelectedRow: EventEmitter<any> = new EventEmitter();
public gridApi: GridApi;
public gridColumnApi;
public printPending: boolean = true;
public showColumnTools: boolean;
public showColumnVisibilityTools: boolean;
public showFilterTools: boolean = true;
private groupDefaultExpanded;
private hoverNode = null;
private isControlPressed: boolean;
private newGroupsCounter: number = 0;
private autoGroupColumnDef: ColDef = {
rowDrag: true,
headerName: "Group",
width: 250,
suppressMovable: true,
cellRendererParams: {
suppressCount: true,
},
valueFormatter: (params) => {
if (!params.data.properties.checkpointList) return params.value;
return params.value + ' (' + (params.data.subGroups ? params.data.subGroups.length : 0) + ')'
+ '(' + (params.data.properties.checkpointList ? params.data.properties.checkpointList.length : 0) + ') ';
},
cellClassRules: {
"hover-over": (params) => {
return params.node === this.hoverNode;
},
"checkpointGroup-title": (params) => {
return this.isCheckpointGroup(params.node.data);
}
}
};
addRowFunction: () => void;
isCheckpointGroup: (nodeData) => boolean = (nodeData) => {
return nodeData && nodeData.properties.checkpointList;
}
getDataPath: (data: any) => any = (data) => {
return data.properties.orgHierarchy;
};
getRowNodeId: (data: any) => any = (data) => {
return (data.properties.parent !== undefined ? data.properties.parent * 1000 : 0) + data.properties.id + (data.properties.component !== undefined ? data.properties.component.id * 100000 : 0);
}
getRowNodeWithUpdatedId: (data: any) => any = (data) => {
return (data.properties.parentId !== undefined ? data.properties.parentId * 1000 : (data.properties.parent !== undefined ? data.properties.parent * 1000 : 0)) + data.properties.id + (data.properties.component !== undefined ? data.properties.component.id * 100000 : 0);
}
public gridOptions: GridOptions = {
enableFilter: this.showFilterTools,
enableColResize: true,
animateRows: true,
cacheQuickFilter: this.showFilterTools,
treeData: true,
quickFilterText: this.quickFilterInput ? this.quickFilterInput.nativeElement.value : '',
colResizeDefault: 'shift',
groupDefaultExpanded: this.groupDefaultExpanded,
rowSelection: 'single',
rowDeselection: true,
defaultColDef: {
filter: "agTextColumnFilter"
},
// components: this.components,
getDataPath: this.getDataPath,
getRowNodeId: this.getRowNodeId,
autoGroupColumnDef: this.autoGroupColumnDef,
deltaRowDataMode: true,
onModelUpdated: () => {
if (this.gridApi && this.columnDefs) {
this.gridColumnApi.autoSizeColumn('ag-Grid-AutoColumn');
this.adjustColumnsToFitWindow();
}
},
onSelectionChanged: (event) => {
let selectedRows = event.api.getSelectedNodes();
let selectedRow = selectedRows && selectedRows.length > 0 ? selectedRows[0] : undefined;
if (selectedRow && this.isCheckpointGroup(selectedRow.data)) {
this.onSelectedRow.emit(selectedRow);
} else {
this.onSelectedRow.emit(undefined);
}
},
};
constructor(
events: Events,
public http: Http,
public templateService: TemplateServiceProvider,
public toastController: ToastController,
public alertCtrl: AlertController,
) {
super(events, [
{ eventName: 'datatable:updateList', callbackFunction: () => this.onLoadRow.emit() },
{ eventName: 'datatable:resizeTable', callbackFunction: () => this.gridApi.sizeColumnsToFit() }
])
this.groupDefaultExpanded = -1;
}
ngOnInit() {
super.subscribeEvents();
this.subscribeEvents();
}
subscribeEvents() {
this.addRowFunction = () => { this.onAddRow.emit() };
window.onresize = () => this.adjustColumnsToFitWindow();
document.addEventListener('keydown', (evt: any) => {
evt = evt || window.event;
if ((evt.keyCode && evt.keyCode === 17) || (evt.which && evt.which === 17)) this.isControlPressed = !this.isControlPressed;
});
}
updateRowData(rowData) {
this.gridApi.setRowData(rowData);
this.gridApi.clearFocusedCell();
this.reAssignSortProperty();
}
onGridReady(params) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.adjustColumnsToFitWindow();
if (!this.rowData || this.rowData.length === 0) this.gridApi.hideOverlay()
}
onRowDragMove(event) {
this.setHoverNode(event);
}
onRowDragLeave() {
this.setHoverNode(undefined);
}
setHoverNode(event) {
let overNode = event ? event.overNode : undefined;
if (this.hoverNode === overNode) return;
var rowsToRefresh = [];
if (this.hoverNode) {
rowsToRefresh.push(this.hoverNode);
}
if (overNode) {
rowsToRefresh.push(overNode);
}
this.hoverNode = overNode;
this.refreshRows(rowsToRefresh);
}
refreshRows(rowsToRefresh) {
var params = {
rowNodes: rowsToRefresh,
force: true
};
this.gridApi.refreshCells(params);
}
onRowDragEnd(event) {
let toIndex;
let overNode = event.overNode;
let movingNode = event.node;
let movingData = movingNode.data;
if (overNode === movingNode) return;
if (!overNode) {
if (this.isCheckpointGroup(movingData)) {
overNode = (<any>this.gridApi.getModel()).rootNode;
toIndex = this.rowData.length;
} else {
return;
}
}
let overData = overNode.data;
let fromIndex = this.rowData.indexOf(movingData);
toIndex = toIndex ? toIndex : this.rowData.indexOf(overData) + 1;
let newParentNode = (!overNode.data || this.isCheckpointGroup(overNode.data)) ? overNode : overNode.parent;
if (overData && (overData.properties.parentId === 0 || (!overData.properties.parentId && overData.properties.parent === 0)) && this.isCheckpointGroup(movingData) && this.isControlPressed) {
overNode = (<any>this.gridApi.getModel()).rootNode;
newParentNode = (!overNode.data || this.isCheckpointGroup(overNode.data)) ? overNode : overNode.parent;
} else if (overData && this.isControlPressed) {
newParentNode = overNode.parent;
}
if (toIndex > fromIndex) toIndex--;
let oldParentNode = movingNode.parent;
let newParentPath = (newParentNode.data && this.isCheckpointGroup(newParentNode.data)) ? newParentNode.data.properties.orgHierarchy : [];
let needToChangeParent = !this.arePathsEqual(newParentPath, movingData.properties.orgHierarchy);
if (fromIndex === toIndex && !needToChangeParent) return;
if (this.isInvalidMoveTo(movingNode, newParentNode)) {
new Toast(this.toastController).showToast('Invalid Move');
return;
}
if (needToChangeParent) {
if (this.checkNodeExistsInParent(movingData, newParentNode)) return;
let updatedRows = [];
this.moveToPath(newParentPath, movingNode, updatedRows, oldParentNode.data, newParentNode.data || { properties: { id: 0 } });
this.gridApi.updateRowData({ update: updatedRows });
this.refreshRows(this.rowData);
}
let newStore = this.rowData.slice();
this.moveInArray(newStore, fromIndex, toIndex);
this.gridApi.setRowData(newStore);
this.rowData = newStore;
this.setHoverNode(undefined);
}
checkNodeExistsInParent(newRow, newParentNode) {
let cloneRow = _.cloneDeep(newRow);
cloneRow.properties.parentId = newParentNode && newParentNode.data ? newParentNode.data.properties.id : 0;
if (this.isCheckpointGroup(cloneRow) && this.existsInParent(cloneRow)) {
new Toast(this.toastController).showToast('"' + cloneRow.properties.name + '" already exists on "' + (newParentNode.data ? newParentNode.data.properties.name : 'root') + '"');
return true;
}
return false
}
checkNodeExistsInTemplate(newRow) {
if (!this.isCheckpointGroup(newRow) && this.existsInTemplate(newRow)) {
new Toast(this.toastController).showToast('"' + newRow.properties.name + '" already exists on the template');
return true;
}
return false
}
existsInParent(newRow) {
return this.rowData.find(row => this.getRowNodeWithUpdatedId(row) === this.getRowNodeWithUpdatedId(newRow));
}
existsInTemplate(newRow) {
return this.rowData.find(row => row.properties.id === newRow.properties.id);
}
moveInArray(arr, old_index, new_index) {
if (new_index >= arr.length) {
var k = new_index - arr.length + 1;
while (k--) {
arr.push(undefined);
}
}
arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
};
moveToPath(newParentPath, node, allUpdatedNodes, oldParentData?, newParentData?) {
var newChildPath = this.updateNodePath(node.data, newParentPath);
if (newParentData) this.updateParents(node.data, oldParentData, newParentData);
allUpdatedNodes.push(node.data);
if (oldParentData) allUpdatedNodes.push(oldParentData);
if (newParentData) allUpdatedNodes.push(newParentData);
if (node.childrenAfterGroup) this.moveChildrenPaths(node.childrenAfterGroup, newChildPath, allUpdatedNodes);
}
updateNodePath(nodeData, newParentPath) {
var oldPath = nodeData.properties.orgHierarchy;
var fileName = oldPath[oldPath.length - 1];
var newChildPath = newParentPath.slice();
newChildPath.push(fileName);
nodeData.properties.orgHierarchy = newChildPath;
return newChildPath;
}
updateParents(nodeData, oldParentData, newParentData) {
nodeData.properties.parentId = newParentData.properties.id;
if (this.isCheckpointGroup(nodeData)) {
if (oldParentData) oldParentData.subGroups = oldParentData.subGroups.filter(subGroup => subGroup.properties.id !== nodeData.properties.id);
if (newParentData && newParentData.subGroups !== undefined) newParentData.subGroups.push(nodeData);
} else {
if (oldParentData) oldParentData.properties.checkpointList = oldParentData.properties.checkpointList.filter(checkpoint => checkpoint.properties.id !== nodeData.properties.id);
if (newParentData && newParentData.properties.checkpointList) newParentData.properties.checkpointList.push(nodeData);
}
}
moveChildrenPaths(children, newChildPath, allUpdatedNodes) {
children.forEach((child) => {
this.moveToPath(newChildPath, child, allUpdatedNodes);
});
}
isInvalidMoveTo(selectedNode, targetNode) {
let isInvalid = false;
if (targetNode.parent && targetNode.parent.data) {
isInvalid = this.isInvalidMoveTo(selectedNode, targetNode.parent);
if (this.getRowNodeWithUpdatedId(targetNode.parent.data) === this.getRowNodeWithUpdatedId(selectedNode.data)) isInvalid = true;
}
if (targetNode && targetNode.data && this.getRowNodeWithUpdatedId(targetNode.data) === this.getRowNodeWithUpdatedId(selectedNode.data)) isInvalid = true;
return isInvalid;
}
arePathsEqual(path1, path2) {
let newPathLength = path1.length + 1;
let oldPathLength = path2.length;
if (this.isControlPressed && newPathLength === 2 && oldPathLength === 1) return true;
if (newPathLength !== oldPathLength) return false;
var equal = true;
path1.forEach(function (item, index) {
if (path2[index] !== item) {
equal = false;
}
});
return equal;
}
reAssignSortProperty() {
this.gridApi.forEachNode((node) => {
node.data.properties.sort = node.childIndex + 1
})
};
addRows(data) {
let selectedGroupNode = data.selectedGroup;
let groupIndex = selectedGroupNode ? this.rowData.indexOf(selectedGroupNode.data) + 1 : this.rowData.length;
data.selectedRows.forEach((selectedRow, index) => {
let newRowData = _.cloneDeep(selectedRow.data);
newRowData.orgHierarchy = selectedGroupNode ? _.cloneDeep(selectedGroupNode.data.properties.orgHierarchy) : [];
newRowData.orgHierarchy.push(newRowData.name);
newRowData = { properties: newRowData };
newRowData.properties.parent = selectedGroupNode ? selectedGroupNode.data.properties.id : 0;
if (this.isCheckpointGroup(newRowData)) {
if (!this.checkNodeExistsInParent(newRowData, selectedGroupNode)) {
this.newGroupsCounter--;
newRowData.properties.checkpointGroupId = newRowData.properties.id;
newRowData.properties.id = this.newGroupsCounter;
newRowData.subGroups = [];
if (selectedGroupNode && selectedGroupNode.data) selectedGroupNode.data.subGroups.push(newRowData);
this.rowData.splice(groupIndex + index + (selectedGroupNode ? selectedGroupNode.allChildrenCount : 0), 0, newRowData)
}
} else {
if (!this.checkNodeExistsInTemplate(newRowData)) {
newRowData.properties.templateCheckpointGroupCheckpointId = -1;
if (selectedGroupNode && selectedGroupNode.data) selectedGroupNode.data.properties.checkpointList.push(newRowData);
this.rowData.splice(groupIndex + index + (selectedGroupNode ? selectedGroupNode.allChildrenCount : 0), 0, newRowData)
}
}
});
if (selectedGroupNode) data.selectedGroup.expanded = true;
this.updateRowData(this.rowData);
}
deleteRow(row) {
if (row.properties.checkpointList && row.properties.checkpointList.length > 0) {
row.properties.checkpointList.forEach(checkpoint => {
this.deleteRow(checkpoint);
});
}
if (row.subGroups && row.subGroups.length > 0) {
row.subGroups.forEach(subGroup => {
this.deleteRow(subGroup);
});
}
this.deleteByUpdatedParentId(row);
this.updateRowData(this.rowData);
}
deleteByUpdatedParentId(row) {
this.rowData = this.rowData.filter(existingRow => this.getRowNodeWithUpdatedId(existingRow) !== this.getRowNodeWithUpdatedId(row));
}
adjustColumnsToFitWindow() {
if (this.gridApi) this.gridApi.sizeColumnsToFit();
}
onFilterTextBoxChanged() {
this.gridApi.setQuickFilter(this.quickFilterInput.nativeElement.value);
}
exportCsv() {
let params = {
fileName: 'Rows',
sheetName: 'Rows',
columnSeparator: ';'
};
this.gridApi.exportDataAsCsv(params);
}
print() {
this.setPrinterFriendly();
this.printPending = true;
// if (this.gridApi.isAnimationFrameQueueEmpty()) {
this.onAnimationQueueEmpty({ api: this.gridApi });
// }
}
onAnimationQueueEmpty(event) {
if (this.printPending) {
this.printPending = false;
this.printTable();
}
}
printTable() {
// let rest = <any>document.querySelector("ion-content :not(#grid)");
// rest.style.display = 'none';
print();
}
setPrinterFriendly() {
let eGridDiv = <any>document.getElementById("grid");
let preferredWidth = this.gridApi.getPreferredWidth();
preferredWidth += 2;
eGridDiv.style.width = preferredWidth + "px";
eGridDiv.style.height = "";
this.gridApi.setGridAutoHeight(true);
}
}
The html:
<ion-content padding>
<ion-item class="generic-tools-wrapper">
<div>
<input type="text" #quickFilterInput placeholder="Filter..." (input)="onFilterTextBoxChanged()" />
<button ion-button small type="button" icon-only (click)="exportCsv()">
<ion-icon name="list-box"></ion-icon>
</button>
<button ion-button small type="button" icon-only (click)="print()">
<ion-icon name="print"></ion-icon>
</button>
<button ion-button small [color]="isControlPressed ? 'danger': 'primary'" type="button" icon-only (click)="isControlPressed = !isControlPressed">
<ion-icon name="return-right"></ion-icon>
</button>
</div>
</ion-item>
<ion-label> <strong>Attention!</strong> The grouping option is <strong>{{isControlPressed ? 'deactivated':
'activated'}}</strong>,
elements
dragged over a group will be put <strong>{{isControlPressed ? 'next to': 'inside'}} that group</strong>. Press
<strong>Control</strong> to switch this option. </ion-label>
<div style="height: 90%;box-sizing: border-box; ">
<ag-grid-angular id="grid" style="width: 100%; height: 100%;" class="ag-theme-material" [rowData]="rowData"
[columnDefs]="columnDefs" [gridOptions]="gridOptions" (gridReady)="onGridReady($event)" (rowDragMove)="onRowDragMove($event)"
(rowDragEnd)="onRowDragEnd($event)" (rowDragLeave)="onRowDragLeave($event)" (viewportChanged)="adjustColumnsToFitWindow()">
</ag-grid-angular>
</div>
</ion-content>

Refresh sticky mobile leaderboard ad slot by changing the content URL in infinite scroll

I want to refresh sticky mobile leaderboard slot when the URL changes in infinite scroll. What do you think is the best way to go? Please let me know if you have any suggestions.
class DFPAds {
constructor() {
this.slots = [];
this.onScroll = throttle(this.loopAds, 300);
this.addEvents();
this.createAdObject = this.createAdObject.bind(this);
this.createSlotForAd = this.createSlotForAd.bind(this);
this.displayAd = this.displayAd.bind(this);
}
static get() {
return DFPAds._instance;
}
static set() {
if (!DFPAds._instance) {
DFPAds._instance = new DFPAds();
return DFPAds._instance;
} else {
throw new Error("DFPAds: instance already initialized");
}
}
addEvents() {
window.addEventListener("scroll", e => this.onScroll());
}
loopAds() {
this.slots.map(slot => this.displayAd(slot));
}
createAdObject(ad) {
let id = ad.id;
let attributes = getDataSet(ad);
let sizes = JSON.parse(attributes.sizes);
let sizeMapping;
if (attributes.sizemapping) {
attributes.sizemapping.length
? (sizeMapping = JSON.parse(attributes.sizemapping))
: (sizeMapping = null);
}
attributes.id = id;
attributes.sizes = sizes;
attributes.sizemapping = sizeMapping;
return attributes;
}
createSlotForAd(adObject) {
let {
id,
adtype,
position,
slotname,
sizes,
sizemapping,
shouldlazyload,
pagenumber,
pageid
} = adObject;
googletag.cmd.push(() => {
let slot = googletag.defineSlot(slotname, sizes, id);
if(position){
slot.setTargeting("position", position);
}
if(pagenumber){
slot.setTargeting("pagenumber", pagenumber);
}
if(pageid){
slot.setTargeting("PageID", pageid)
}
if (sizemapping) {
let mapping = googletag.sizeMapping();
sizemapping.map(size => {
mapping.addSize(size[0], size[1])
});
slot.defineSizeMapping(mapping.build());
}
slot.addService(googletag.pubads());
googletag.display(id);
shouldlazyload
? this.slots.push({ slot: slot, id: id })
: googletag.pubads().refresh([slot]);
console.log("SlotTop", slot)
});
}
displayAd(slot) {
console.log("Slottwo", slot)
let item = document.getElementById(slot.id);
if (item) {
let parent = item.parentElement;
let index = this.slots.indexOf(slot);
let parentDimensions = parent.getBoundingClientRect();
if (
(parentDimensions.top - 300) < window.innerHeight &&
parentDimensions.top + 150 > 0 &&
parent.offsetParent != null
) {
googletag.cmd.push(function() {
googletag.pubads().refresh([slot.slot]);
});
this.slots.splice(index, 1);
}
}
}
setUpAdSlots(context = document) {
let ads = [].slice.call(context.getElementsByClassName("Ad-data"));
if (ads.length) {
ads.map(ad => compose(this.createSlotForAd, this.createAdObject)(ad));
}
}
}
export default DFPAds;
And this is my Infinite Scroll code:
export default class InfiniteScroll {
constructor() {
this._end = document.getElementById('InfiniteScroll-End');
this._container = document.getElementById('InfiniteScroll-Container');
if(!this._end || !this._container)
return;
this._articles = { };
this._triggeredArticles = [];
this._currentArticle = '';
this._apiUrl = '';
this._count = 1;
this._timedOut = false;
this._loading = false;
this._ended = false;
this._viewedParameter = "&alreadyViewedContentIds=";
this._articleSelector = "InfiniteScroll-Article-";
this._articleClass = "Article-Container";
this.setStartData();
this.onScroll = throttle(this.eventScroll, 200);
this.addEvents();
}
addEvents(){
setTimeout(()=>{
window.addEventListener('scroll', (e) => this.onScroll() );
}, 2000);
}
addToStore(article){
this._articles["a" + article.id] = article;
}
addToTriggeredArticles(id){
this._triggeredArticles.push(id);
}
getRequestUrl(){
return this._apiUrl + this._viewedParameter + Object.keys(this._articles).map(key => this._articles[key].id).join();
}
getLastArticle(){
return this._articles[Object.keys(this._articles)[Object.keys(this._articles).length-1]];
}
setStartData() {
let dataset = getDataSet(this._container);
if(dataset.hasOwnProperty('apiurl')){
let article = Article.get();
if(article){
this._apiUrl = dataset.apiurl;
this._currentArticle = "a" + article.id;
this.addToStore(article);
}else{
throw(new Error('Infinite Scroll: Article not initialized.'));
}
}else{
throw(new Error('Infinite Scroll: Start object missing "apiurl" property.'));
}
}
eventScroll() {
if(this.isApproachingNext()){
this.requestNextArticle();
}
if(!this.isMainArticle(this._articles[this._currentArticle].node)){
this.updateCurrentArticle();
}
}
eventRequestSuccess(data){
this._loading = false;
if(data != ''){
if(data.hasOwnProperty('Id') && data.hasOwnProperty('Html') && data.hasOwnProperty('Url')){
this.incrementCount();
let node = document.createElement('div');
node.id = this._articleSelector + data.Id;
node.innerHTML = data.Html;
node.className = this._articleClass;
this._container.appendChild(node);
this.initArticleUpNext({
img: data.Img,
title: data.ArticleTitle,
category: data.Category,
target: node.id
});
this.addToStore(
new Article({
id: data.Id,
node: node,
url: data.Url,
title: data.Title,
count: this._count,
nielsenProps: {
section: data.NeilsenSection,
sega: data.NeilsenSegmentA,
segb: data.NeilsenSegmentB,
segc: data.NeilsenSegmentC
}
})
);
}else{
this._ended = true;
throw(new Error('Infinite Scroll: Response does not have an ID, Url and HTML property'));
}
}else{
this._ended = true;
throw(new Error('Infinite Scroll: No new article was received.'));
}
}
eventRequestError(response){
this._loading = false;
this._ended = true;
throw(new Error("Infinite Scroll: New article request failed."));
}
requestNextArticle(){
if(!this._loading){
this._loading = true;
return API.requestJSON(this.getRequestUrl())
.then(
(response)=>{this.eventRequestSuccess(response)},
(response)=>{this.eventRequestError(response)}
);
}
}
triggerViewEvent(article){
if(article.count > 1 && !this.isAlreadyTriggeredArticle(article.id)){
this.addToTriggeredArticles(article.id);
Tracker.pushView(article.url, article.count);
if(isFeatureEnabled('Nielsen') && Nielsen.get()){
Nielsen.get().eventInfiniteScroll({
id: article.id,
url: article.url,
section: article.nielsenProps.section,
sega: article.nielsenProps.sega,
segb: article.nielsenProps.segb,
segc: article.nielsenProps.segc
});
NielsenV60.trackEvent(article.title);
}
}
}
updateCurrentArticle(){
Object.keys(this._articles).map( key => {
if(this._currentArticle !== key && this.isMainArticle(this._articles[key].node)){
this._currentArticle = key;
this.updateUrl(this._articles[key]);
this.triggerViewEvent(this._articles[key]);
}
});
}
updateUrl(article){
try{
if(history.replaceState){
if(window.location.pathname !== article.url){
history.replaceState('', article.title, article.url);
}
}
}catch(e){}
}
incrementCount(){
this._count = this._count + 1;
}
initArticleUpNext(data){
this.getLastArticle().initUpNext(data);
}
isApproachingNext(){
return window.pageYOffset > this._end.offsetTop - (window.innerHeight * 2) && !this._ended && this._end.offsetTop >= 100;
}
isMainArticle(node){
if(node.getBoundingClientRect){
return (node.getBoundingClientRect().top < 80 && node.getBoundingClientRect().bottom > 70);
}else{
return false;
}
}
isAlreadyTriggeredArticle(id){
return this._triggeredArticles.indexOf(id) > -1;
}
}

TypeError: 'undefined' is not a function (evaluating 'ime.registIMEKey()')

Despite of setting and defining everything in Samsung smart TV SDK 4.0 I am getting this error:
TypeError: 'undefined' is not a function (evaluating 'ime.registIMEKey()')
Please help!
CODE:
var widgetAPI = new Common.API.Widget();
var tvKey = new Common.API.TVKeyValue();
var wapal_magic =
{
elementIds: new Array(),
inputs: new Array(),
ready: new Array()
};
/////////////////////////
var Input = function (id, previousId, nextId) {
var previousElement = document.getElementById(previousId),
nextElement = document.getElementById(nextId);
var installFocusKeyCallbacks = function () {
ime.setKeyFunc(tvKey.KEY_UP, function (keyCode) {
previousElement.focus();
return false;
});
ime.setKeyFunc(tvKey.KEY_DOWN, function (keyCode) {
nextElement.focus();
return false;
});
ime.setKeyFunc(tvKey.KEY_RETURN, function (keyCode) {
widgetAPI.blockNavigation();
return false;
});
ime.setKeyFunc(tvKey.KEY_EXIT, function (keyCode) {
widgetAPI.blockNavigation();
return false;
});
}
var imeReady = function (imeObject) {
installFocusKeyCallbacks();
wapal_magic.ready(id);
},
ime = new IMEShell(id, imeReady, 'en'),
element = document.getElementById(id);
}
wapal_magic.createInputObjects = function () {
var index,
previousIndex,
nextIndex;
for (index in this.elementIds) {
previousIndex = index - 1;
if (previousIndex < 0) {
previousIndex = wapal_magic.inputs.length - 1;
}
nextIndex = (index + 1) % wapal_magic.inputs.length;
wapal_magic.inputs[index] = new Input(this.elementIds[index],
this.elementIds[previousIndex], this.elementIds[nextIndex]);
}
};
wapal_magic.ready = function (id) {
var ready = true,
i;
for (i in wapal_magic.elementIds) {
if (wapal_magic.elementIds[i] == id) {
wapal_magic.ready[i] = true;
}
if (wapal_magic.ready[i] == false) {
ready = false;
}
}
if (ready) {
document.getElementById("txtInp1").focus();
}
};
////////////////////////
wapal_magic.onLoad = function()
{
// Enable key event processing
//this.enableKeys();
// widgetAPI.sendReadyEvent();
this.initTextBoxes(new Array("txtInp1", "txtInp2"));
};
wapal_magic.initTextBoxes = function(textboxes){
this.elementIds = textboxes;
for(i=0;i<this.elementIds.length;i++){
this.inputs[i]=false;
this.ready[i]=null;
}
this.createInputObjects();
widgetAPI.registIMEKey();
};
wapal_magic.onUnload = function()
{
};
wapal_magic.enableKeys = function()
{
document.getElementById("anchor").focus();
};
wapal_magic.keyDown = function()
{
var keyCode = event.keyCode;
alert("Key pressed: " + keyCode);
switch(keyCode)
{
case tvKey.KEY_RETURN:
case tvKey.KEY_PANEL_RETURN:
alert("RETURN");
widgetAPI.sendReturnEvent();
break;
case tvKey.KEY_LEFT:
alert("LEFT");
break;
case tvKey.KEY_RIGHT:
alert("RIGHT");
break;
case tvKey.KEY_UP:
alert("UP");
break;
case tvKey.KEY_DOWN:
alert("DOWN");
break;
case tvKey.KEY_ENTER:
case tvKey.KEY_PANEL_ENTER:
alert("ENTER");
break;
default:
alert("Unhandled key");
break;
}
};
The registIMEKey method is part of the Plugin API.
var pluginAPI = new Common.API.Plugin();
pluginAPI.registIMEKey();
See: http://www.samsungdforum.com/Guide/ref00006/common_module_plugin_object.html#ref00006-common-module-plugin-object-registimekey
Edit: Updated to add code solution.
widgetAPI no contains method registIMEKey();, it contains in IMEShell.

highcharts can't render

I use Ajax to get data, when I debug with firebug, the result shows highcharts option's data has data. But the chart can't render correctly. The charts background is rended correctely, but there is no chart.
here is my code.
// # author:wang
var chart;
var element;
var chart_type_element;
var y_title_1;
var y_title_2;
var y_title_3;
var date = new Date();
var y = date.getUTCFullYear();
var m = date.getUTCMonth();
var d = date.getUTCDate()-1;
var h = date.getUTCHours();
var minute = date.getUTCMinutes();
/**
* 返回图表的类型
*
*/
function chart_type(element){
var type;
var wind = '风向风速';
var t_h = '温湿度';
if ( element== 'wind' ){
type = wind;
} else if ( element == 't_h') {
type = t_h;
}
return type;
}
/**
*
*return y-axis title
*
*/
function y_title(element, serie){
var title;
if ( element== 'wind' ){
switch (serie){
case 1: title = '风速'; break;
case 2: title = '阵风'; break;
case 3: title = '风向'; break;
}
} else if ( element == 't_h') {
switch (serie){
case 1: title = '温度'; break;
case 2: title = '湿度'; break;
default: title = '';
}
}
return title;
}
function getLocTime(nS) {
return new Date(parseInt(nS)).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
}
/**
* 气压配置选项
*/
var option_p = {
chart: {
renderTo: 'station_curve',
zoomType: 'x'
},
title:{
text:'气压序列图'
},
subtitle: {
text: '信科气象台'
},
xAxis: {
type: 'datetime',
maxZoom: 3600000, // one hour
title: {
text: null
}
},
yAxis: {
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}],
min:980,
max:1040
},
tooltip: {
formatter: function() {
return getLocTime(this.x) +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'left',
x: 220,
verticalAlign: 'top',
y: 30,
floating: true,
backgroundColor: '#FFFFFF'
},
series: [{
name: '海平面气压',
color: '#4572A7',
type: 'line',
pointInterval: 60 * 1000,
pointStart: Date.UTC(y,m,d,h,minute),
marker: {
enabled: false
}
}, {
name: '甲板气压',
type: 'line',
color: '#AA4643',
pointInterval: 60 * 1000,
pointStart: Date.UTC(y,m,d,h,minute),
marker: {
enabled: false
}
}/*, {
name: '3',
color: '#89A54E',
pointInterval: 60 * 1000,
pointStart: Date.UTC(y,m,d,h,minute),
type: 'spline',
marker: {
enabled: false
}
}*/]
};
function draw_curve(platformID,element){
option.series[0].data = [];
option.series[1].data = [];
option_th.series[0].data = [];
option_th.series[1].data = [];
jQuery.getJSON('get_last_3d.php',{platformID:platformID,element:element}, function(data) {
var serie=[];
var serie1=[];
if (element == 'wind_dir'){
$.each(data,function(i,value){
serie[i]=parseInt(value.wd);
});
option.series[0].data = serie.reverse();
} else if (element == 'wind_speed'){
$.each(data,function(i,value){
serie[i]=parseInt(value.ws);
serie1[i]=parseInt(value.ws_max);
});
option_wind_speed.series[0].data = serie.reverse();
option_wind_speed.series[1].data = serie1.reverse();
} else if (element == 't_h') {
$.each(data,function(i,value){
serie[i]=parseInt(value.t);
serie1[i]=parseInt(value.h);
});
option_th.series[0].data = serie.reverse();
option_th.series[1].data = serie1.reverse();
} else if (element == 'p') {
$.each(data,function(i,value){
serie[i]=parseInt(value.sea_p);
serie1[i]=parseInt(value.deck_p);
});
option_p.series[0] = serie.reverse();
option_p.series[1] = serie1.reverse();
} else if (element == 'wave_height') {
$.each(data,function(i,value){
serie[i]=parseInt(value.wave_height);
});
option.series[0].data = serie.reverse();
} else if (element == 'visibility') {
$.each(data,function(i,value){
serie[i]=parseInt(value.visibility);
});
option.series[0].data = serie.reverse();
} else if (element == 'cloudheight') {
$.each(data,function(i,value){
serie[i]=parseInt(value.cloud_height);
});
option.series[0].data = serie.reverse();
}
switch(element){
case 'p' :
chart = new Highcharts.Chart(option_p);
break;
case 't_h':
chart = new Highcharts.Chart(option_th);
break;
case 'wind_speed':
chart = new Highcharts.Chart(option_wind_speed);
break;
default:
chart = new Highcharts.Chart(option);
}
/* old code, will be replaced with switch
if (element == 'p')
chart = new Highcharts.Chart(option_p);
else {
chart = new Highcharts.Chart(option);
}
*/
});
}
$( function(){
draw_curve(105,'t_h');
})//end of jquery function
![the chart][1]
thank you advance
The reason it doesn't work is because you didn't provide the values for y,m,d,h,minute for the Date.UTC(y,m,d,h,minute) in the pointStart property for your series. See working: http://jsfiddle.net/LzfM3/