No rows rendered by embertable but colums show up - model-view-controller

I am using the newest ember and embertable. Tried to use example from the page and rewrite it for use in my MVC project. Problem is that rows will not show but the columns show.
Is this a problem with the new ember version?
Edit: Putting som more information here.
HTML
<script type="text/x-handlebars" data-template-name="application">
<div class='presentation-container'>
{{view Ember.Table.TablesContainer controllerBinding="tableController"}}
</div>
</script>
The output(No rows =/ )
Date Entry Low Open Volume High Close
EmployeetaskController
App.EmployeetasksController = Ember.Controller.extend({
tableController: Ember.computed(function () {
return Ember.get('App.EmployeetasksController.TableController').create();
}).property() });
App.EmployeetasksController.LazyDataSource = Ember.ArrayProxy.extend({
init: function () {
console.log('EmployeetasksController.LazyDataSource init');
enter code here this._super();
},
objectAt: function (idx) {
console.log("Lager rad");
var date, row;
row = this.get('content')[idx];
if (row) {
return row;
}
date = new Date();
date.setDate(date.getDate() + idx);
row = {
index: idx,
date: date,
open: Math.random() * 100 - 50,
high: Math.random() * 100 - 50,
low: Math.random() * 100 - 50,
close: Math.random() * 100 - 50,
volume: Math.random() * 1000000
};
this.get('content')[idx] = row;
return row;
}, });
App.EmployeetasksController.TableController = Ember.Table.TableController.extend({
init: function () {
console.log('EmployeetasksController.TableController init');
this._super();
},
hasHeader: true,
hasFooter: true,
numFixedColumns: 0,
numRows: 500000,
rowHeight: 30,
columns: Ember.computed(function () {
var columnNames, columns, dateColumn, entryColumn;
columnNames = ['open', 'high', 'low', 'close', 'volume'];
entryColumn = Ember.Table.ColumnDefinition.create({
columnWidth: 100,
headerCellName: 'Entry',
contentPath: 'index'
});
dateColumn = Ember.Table.ColumnDefinition.create({
columnWidth: 150,
headerCellName: 'Date',
getCellContent: function (row) {
return row['date'].toDateString();
}
});
columns = columnNames.map(function (key, index) {
var name;
name = key.charAt(0).toUpperCase() + key.slice(1);
return Ember.Table.ColumnDefinition.create({
columnWidth: 100,
headerCellName: name,
getCellContent: function (row) {
return row[key].toFixed(2);
}
});
});
columns.unshift(dateColumn);
columns.unshift(entryColumn);
return columns;
}).property(),
content: Ember.computed(function () {
console.log("Lager array");
return App.EmployeetasksController.LazyDataSource.create({
content: new Array(this.get('numRows'))
});
}).property('numRows') });
The view
App.EmployeetasksView = Ember.View.extend({
classNames: 'ember-app',
templateName: 'employeetasks'
});

Outdated ember and handlebars fixed it.

Related

Odd animation with multiple series

I was trying to adapt the spline animation for time series (https://www.highcharts.com/demo/dynamic-update) for multiple series.
I modified the example here https://jsfiddle.net/2wj3fquL/
Highcharts.chart('container', {
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series;
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.random();
series[0].addPoint([x, y], true, true);
y = Math.random();
series[1].addPoint([x, y], true, true);
}, 1000);
}
}
},
time: {
useUTC: false
},
title: {
text: 'Live random data'
},
accessibility: {
announceNewData: {
enabled: true,
minAnnounceInterval: 15000,
announcementFormatter: function (allSeries, newSeries, newPoint) {
if (newPoint) {
return 'New point added. Value: ' + newPoint.y;
}
return false;
}
}
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
headerFormat: '<b>{series.name}</b><br/>',
pointFormat: '{point.x:%Y-%m-%d %H:%M:%S}<br/>{point.y:.2f}'
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}, {
name: 'other data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
Unfortunately the effect is odd since one series moves smooth while the other doesn't ...
How could I solve this problem?
Thanks
That is because the chart is redrawn twice. Disable redraw in the first addPoint method call.
events: {
load: function() {
...
setInterval(function() {
...
series[0].addPoint([x, y], false, true);
series[1].addPoint([x, y], true, true);
}, 1000);
}
}
Live demo: https://jsfiddle.net/BlackLabel/0n2yw57m/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Series#addPoint

Referring to a child view from the parent view on click or tap event in TI

In appcelerator TI code - I have a month scrollable view to which I have added week views and to which I have added days as views.
The expectation on click event of a day I should be able to retrieve properties of the date. However on singletap event I am getting reference to the week view and not able to get the child view "days view. how can I get a reference to the days view on single tap to click event?
Code -Widget.js
var args = arguments[0] || {};
var Moment = require('alloy/moment');
var ROWS = 6;
var COLUMNS = 7;
_.defaults(args, {
// Data
current_date: Moment(),
active_dates: [],
min_date: Moment().subtract(6, 'months'),
max_date: Moment().add(6, 'months'),
// Style
backgroundColor: 'transparent',
dateBackgroundColor: 'transparent',
todayBackgroundColor: '#af80',
dateTextColor: '#fff',
todayTextColor: '#000',
activePinColor: '#f39911',
inactivePinColor: 'transparent',
selectedBackgroundColor: '#60f39911',
fontFamily: '',
// Behaviour
allowInactiveSelection: false,
fillMonth: false,
enablePastDays: false
});
var active_dates = args.active_dates ? getMomentDates(args.active_dates) : [];
var current_page = 0;
/////////////
// Methods //
/////////////
function refreshArrows() {
$.leftBtn.opacity = current_page <= 0 ? 0.4 : 1;
$.rightBtn.opacity = current_page >= $.monthScroll.views.length - 1 ? 0.4 : 1;
}
function getDayLabels() {
var days = Moment.weekdaysMin();
days.push(days.shift()); // Moment week has Sunday at index 0
_.each(days, function(day, i) {
var width = Math.floor($.calendar.rect.width / COLUMNS);
var $label = $.UI.create('Label', {
classes: ['dayLabel'],
width: width,
text: day.charAt(0),
left: i * width,
font: {
fontFamily: args.fontFamily
}
});
$.dayLabels.add($label);
});
}
function getMomentDates(dates) {
return _.map(dates, function(date) {
return Moment(date);
});
}
function isInMomentsList(date, dates) {
return _.find(dates, function(day) {
return date.isSame(day, 'day');
});
}
function getDayContainer(number) {
var $this = $.UI.create('View', {
classes: ['day'],
width: Math.floor($.monthScroll.rect.width / COLUMNS),
height: Math.floor($.monthScroll.rect.height / ROWS),
backgroundColor: args.dateBackgroundColor,
opacity: 1,
date: null,
active: null,
});
$this.add($.UI.create('Label', {
classes: ['dayNumber'],
color: '#fff',
text: number,
font: {
fontFamily: args.fontFamily
}
}));
$this.add($.UI.create('View', {
classes: ['dayDot'],
backgroundColor: 'transparent'
}));
return $this;
}
function setItemDate($item, date) {
$item.date = date;
$item.children[0].text = date.date();
}
function setItemActive($item, active) {
$item.active = active;
$item.children[1].backgroundColor = active ? args.activePinColor : args.inactivePinColor;
}
function setItemToday($item, is_today) {
$item.backgroundColor = is_today ? args.todayBackgroundColor : args.dateBackgroundColor;
$item.children[0].color = is_today ? args.todayTextColor : args.dateTextColor;
}
function setItemCurrent($item, current) {
$item.opacity = current ? 1 : 0.5;
}
function getMonthView(month, year) {
var month_rows = [];
var start_date = Moment().month(month).year(year).startOf('month').startOf('week');
var end_date = Moment().month(month).year(year).endOf('month').endOf('week');
// Month skeleton
var $month_view = $.UI.create('View', {
classes: ['month'],
month: month,
year: year,
backgroundColor: args.backgroundColor,
ready: false
});
// Month activity indicator
var $loader = Ti.UI.createActivityIndicator({
style: OS_IOS ? Ti.UI.iPhone.ActivityIndicatorStyle.BIG : Ti.UI.ActivityIndicatorStyle.BIG,
center: {
x: '50%',
y: '50%'
}
});
$month_view.add($loader);
$month_view.__loader = $loader;
$loader.show();
return $month_view;
}
function buildMonth($month_view, dates) {
if (!$month_view || $month_view.ready) return;
var start_date = Moment().month($month_view.month).year($month_view.year).startOf('month').startOf('week');
var end_date = Moment().month($month_view.month).year($month_view.year).endOf('month').endOf('week');
var $days_container = Ti.UI.createView({
height: Ti.UI.FILL,
width: Ti.UI.FILL
});
// Separators
for (var i = 0; i < ROWS; i++) {
$days_container.add($.UI.create('View', {
classes: ['hr'],
top: (i+1) * Math.floor($.monthScroll.rect.height / ROWS)
}));
}
// Add day containers
for (var d = 0; d < ROWS*COLUMNS; d++) {
var curday = Moment(start_date).add(d, 'days');
// If fillMonth is disabled, add only this month's days
if (curday.month() === $month_view.month || args.fillMonth == true) {
var $curview = getDayContainer(curday.date());
var row = Math.floor(d/COLUMNS);
var col = d % COLUMNS;
setItemDate($curview, curday);
setItemActive($curview, isInMomentsList(curday, dates));
setItemCurrent($curview, !curday.isBefore(Moment(), 'day') || (args.enablePastDays == true && (curday.month() === $month_view.month)));
setItemToday($curview, curday.isSame(Moment(), 'day'));
$curview.top = row * ($curview.height);
$curview.left = col * ($curview.width);
$days_container.add($curview);
}
}
$month_view.add($days_container);
$month_view.ready = true;
$month_view.__loader.hide();
}
function buildCalendar() {
$.main.removeEventListener('postlayout', buildCalendar);
// Add top labels
getDayLabels();
// Create the calendar views
var curmonth_index = -1; var i = 0;
for (var m = Moment(args.min_date); m.diff(Moment(args.max_date)) <= 0; m.add(1, 'months')) {
if (m.isSame(Moment(), 'month')) curmonth_index = i;
var monthview = getMonthView(m.month(), m.year());
$.monthScroll.addView(monthview);
i++;
}
$.monthScroll.currentPage = current_page = curmonth_index > 0 ? curmonth_index : 0;
refreshCalendarMonth(current_page);
refreshArrows();
}
function refreshCalendarMonth(m) {
var month_date = Moment().month($.monthScroll.views[m].month).year($.monthScroll.views[m].year);
$.monthName.text = month_date.format('MMMM').toUpperCase();
$.monthYear.text = month_date.format('YYYY');
buildMonth($.monthScroll.views[m], args.active_dates);
if (current_page - 1 > -1) buildMonth($.monthScroll.views[m-1], args.active_dates);
if (current_page + 1 < 12) buildMonth($.monthScroll.views[m+1], args.active_dates);
}
///////////////
// Listeners //
///////////////
$.main.addEventListener('postlayout', buildCalendar);
$.monthScroll.addEventListener('scroll', function(e) {
if (e.currentPage === current_page) return;
current_page = e.currentPage;
refreshArrows();
refreshCalendarMonth(current_page);
});
$.monthScroll.addEventListener('click', function(e) {
if (!e.source.date || (!e.source.active && !args.allowInactiveSelection) || (args.enablePastDays == false && e.source.date.isBefore(Moment(), 'day'))) return;
e.source.animate({ backgroundColor: args.selectedBackgroundColor, duration: 150, autoreverse: true });
$.trigger('selected', {
date: e.source.date,
active: e.source.active
});
});
$.leftBtn.addEventListener('click', function() {
$.monthScroll.movePrevious();
});
$.rightBtn.addEventListener('click', function() {
$.monthScroll.moveNext();
});
//////////
// Init //
//////////
$.monthName.font = {
fontFamily: args.fontFamily,
fontWeight: 'bold'
};
$.monthYear.font = {
fontFamily: args.fontFamily,
fontWeight: 'light'
};
Widget.xml
<Alloy>
<Window backgroundColor="#110ee1" class="container" exitOnClose="true" id="widget" title="DailyRead" top="0">
<View id="main">
<View class="bar" id="header">
<View class="hr" top="0"/>
<View class="ctrlBtn" id="leftBtn">
<ImageView id="leftArrow"/>
</View>
<View class="headerText">
<Label id="monthName"/>
<Label id="monthYear"/>
</View>
<View class="ctrlBtn" id="rightBtn">
<ImageView id="rightArrow"/>
</View>
<View bottom="0" class="hr"/>
</View>
<View class="sp1/2"/>
<View id="calendar">
<View id="dayLabels"/>
<View backgroundColor="#fff" class="hr" height="2"/>
<ScrollableView id="monthScroll"/>
</View>
</View>
</Window>
</Alloy>
As far as I understood the question I would add more information to the day view. E.g. if you create everything through a loop just add month, weeks to the day view as a property. Then set all views but the day view to touchEnabled:false and just add the click event to the day view. Then you can read event.source.day/event.source.week/event.source.month inside the click-event.
If that doesn't help please add some example code to your question.

ZoomRange Highstock works not correct?

I made a Highstock diagramm and got aproblem with zooming on the yAxis.
I have a Button and 2 textfield to get the wanted min/max values for the axis. With min:0, max: 100 it works well. With min:0, max:80 it doesn't (max will still be 100 in the Diagramm).
If I use the mouse for zooming it works well (even a min of: 3.7 and a max of 3.894 is possible). But using the mouse is not an Option, because in the later Diagramm there will be 3 yAxes with individual zoom.
$(function () {
var seriesOptions = [],
seriesCounter = 0,
names = ['MSFT', 'AAPL', 'GOOG'];
/**
* Create the chart when all data is loaded
* #returns {undefined}
*/
function createChart() {
$('#container').highcharts('StockChart', {
rangeSelector: {
selected: 4
},
chart:{
zoomType: 'xy'
},
yAxis: [
{
labels: {
format: '{value}',
},
height: '100%',
opposite: false,
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
],
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
},
function(chart){
$('#btn').click(function(){
var min = temp_min.value,
max = temp_max.value;
chart.yAxis[0].setExtremes((min),(max));
});
});
}
$.each(names, function (i, name) {
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?', function (data) {
if(seriesCounter==0){
seriesOptions[i] = {
name: name,
data: data,
yAxis: 0
};
} else {
seriesOptions[i] = {
name: name,
data: data,
yAxis: 0
};
}
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter += 1;
if (seriesCounter === names.length) {
createChart();
}
});
});
});
JSFiddle
Another Question: Is it possible to set up a scrollbar for the yAxis as well?
Thanks for your help, Patrick
This is related with fact that tickInterval is not regular, so is rounded to value (like 100). The solution is using tickPositioner which calculates ticks, based on extremes which you define.
tickPositioner: function (min,max) {
var positions = [],
tick = Math.floor(min),
increment = Math.ceil((max - min) / 5);
for (tick; tick - increment <= max; tick += increment) {
positions.push(tick);
}
return positions;
},
http://jsfiddle.net/6s11kcwd/
The scrollbar is supported only for xAxis.

Kendo treelist - trying to set a column template

I'm working with a Kendo treelist widget, and disappointed to see there's no rowTemplate option as there is on the Kendo grid.
I see a columnTemplate option (i.e. http://docs.telerik.com/kendo-ui/api/javascript/ui/treelist#configuration-columns.template ), but this will affect the entire column.
However, I need to drill into each cell value and set a css color property based on a ratio ( i.e. If value/benchmark < .2, assign <span style='color:red;'> , but my color value is dynamic.
There's a dataBound: and dataBinding: event on the treelist, but I'm still trying to figure out how to intercept each cell value and set the color once I've done my calculation.
var treeOptions = {
dataSource: ds,
columns: colDefs,
selectable: true,
scrollable: true,
resizable: true,
reorderable: true,
height: 320,
change: function (e) {
// push selected dataItem
var selectedRow = this.select();
var row = this.dataItem(selectedRow);
},
dataBound: function (e) {
console.log("dataBinding");
var ds = e.sender.dataSource.data();
var rows = e.sender.table.find("tr");
}
};
and this is where I'm building out the `colDefs' object (column definitions):
function parseHeatMapColumns(data, dimId) {
// Creates the Column Headers of the heatmap treelist.
// typeId=0 is 1st Dimension; typeId=1 is 2nd Dimension
var column = [];
column.push({
"field": "field0",
"title": "Dimension",
headerAttributes: { style: "font-weight:" + 'bold' + ";" },
attributes : { style: "font-weight: bold;" }
});
var colIdx = 1; // start at column 1 to build col headers for the 2nd dimension grouping
_.each(data, function (item) {
if (item.typeId == dimId) {
// Dimension values are duplicated, so push unique values (i.e. trade types may have dupes, whereas a BkgLocation may not).
var found = _.find(column, { field0: item.field0 });
if (found == undefined) {
column.push({
field: "field2",
title: item.field0,
headerAttributes: {
style: "font-weight:" + 'bold'
}
,template: "<span style='color:red;'>#: field2 #</span>"
});
colIdx++;
}
}
});
return column;
}
**** UPDATE ****
In order to embed some logic within the template :
function configureHeatMapColumnDefs(jsonData, cols, model) {
var colDef = '';
var dimId = 0;
var colorProp;
var columns = kendoGridService.parseHeatMapColumns(jsonData, dimId);
// iterate columns and set color property; NB: columns[0] is the left-most "Dimension" column, so we start from i=1.
for (var i = 1; i <= columns.length-1; i++) {
columns[i]['template'] = function (data) {
var color = 'black';
if (data.field2 < 1000) {
color = 'red';
}
else if (data.field2 < 5000) {
color = 'green';
}
return "<span style='color:" + color + ";'>" + data.field2 + "</span>";
};
}
return columns;
}
Advice is appreciated.
Thanks,
Bob
In the databound event you can iterate through the rows. For each row you can get the dataItem associated with it using the dataitem() method (http://docs.telerik.com/kendo-ui/api/javascript/ui/treelist#methods-dataItem)
Once you have the dataitem, calculate your ration and if the row meets the criteria for color, change the cell DOM element:
dataBound: function (e) {
var that = e.sender;
var rows = e.sender.table.find("tr");
rows.each(function(idx, row){
var dataItem = that.dataItem(row);
var ageCell = $(row).find("td").eq(2);
if (dataItem.Age > 30) {
//mark in red
var ageText = ageCell.text();
ageCell.html('<span style="color:red;">' + ageText + '</span>');
}
}
DEMO
UPDATE: you can also do this with a template:
$("#treelist").kendoTreeList({
dataSource: dataSource,
height: 540,
selectable: true,
columns: [
{ field: "Position"},
{ field: "Name" },
{ field: "Age",
template: "# if ( data.Age > 30 ) { #<span style='color:red;'> #= data.Age # </span> #}else{# #= data.Age # #}#"
}
],
});
DEMO

How to move handson table scroll bar to specific row and column..?

I'm trying find out a method or a way by which i can move handson tables scroll bar to specific row and column.
I tried using
selectCell (row: Number, col: Number, rows: Number, cols: Number, scrollToSelection: Boolean (Optional)) but it doesn't seems to work
here is the Fiddle link for it http://jsfiddle.net/hpfvc9bx/
$(document).ready(function () {
function createBigData() {
var rows = []
, i
, j;
for (i = 0; i < 1000; i++) {
var row = [];
for (j = 0; j < 6; j++) {
row.push(Handsontable.helper.spreadsheetColumnLabel(j) + (i + 1));
}
rows.push(row);
}
return rows;
}
var maxed = false
, resizeTimeout
, availableWidth
, availableHeight
, $window = $(window)
, $example1 = $('#example1');
var calculateSize = function () {
if(maxed) {
var offset = $example1.offset();
availableWidth = $window.width() - offset.left + $window.scrollLeft();
availableHeight = $window.height() - offset.top + $window.scrollTop();
$example1.width(availableWidth).height(availableHeight);
}
};
$window.on('resize', calculateSize);
var table = $example1.handsontable({
data: createBigData(),
colWidths: [55, 80, 80, 80, 80, 80, 80], //can also be a number or a function
rowHeaders: true,
colHeaders: true,
fixedColumnsLeft: 2,
fixedRowsTop: 2,
minSpareRows: 1,
stretchH: 'all',
contextMenu: true,
afterChange : function(changes){
console.log(changes);
}
});
$('.maximize').on('click', function () {
maxed = !maxed;
if(maxed) {
calculateSize();
}
else {
$example1.width(400).height(200);
}
$example1.handsontable('render');
});
$("#setSelectedRow").on('click',function(){
console.log(table);
table.select(9,3,12,6,true); // not working as it doesnt move scroll bar to specified column and range
})
function bindDumpButton() {
$('body').on('click', 'button[name=dump]', function () {
var dump = $(this).data('dump');
var $container = $(dump);
console.log('data of ' + dump, $container.handsontable('getData'));
});
}
bindDumpButton();
});
Can anyone please help me on this...
Thanks In advance...
You can move to specific cell using "selectCell" of handsontable.
You have use table.select(...) in $("#setSelectedRow").on('click',function(){....
It won't work as you are using table DOM element but you need to have "instance" of handsontable. That can be done as,
First Way:
var tblInstance = $example1.handsontable('getInstance');
And then apply "selectCell()" as
tblInstance.selectCell(rowNum, colNum);
Second Way:
Use $example1.handsontable("selectCell", rowNum, colNum);
Please refer to fiddle for the second way, in which :
$("#setSelectedRow").on('click',function(){
console.log(table);
$example1.handsontable("selectCell", 9, 5); // select 9th row's 5th column
})
Hope this will help you :)

Resources