google maps marker load via ajax and infocontent - django

In my app I have a google map and I want to add many marker on it and so I load the data via ajax (I'm in Django). I have the probem with infocontent and the 'click' event on the marker load via ajax: When I do 'click' on the marker nothing happened. This is my code:
function initialize() {
var latlng = new google.maps.LatLng({{lat}}, {{long}});
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapCanvas"), myOptions);
var contentString = '<div id="content">{{name}}<br><span style="font-size:10px;">{{road}}</span><br><span style="font-size:10px;">{{city}} ({{prov}})</span></div>';
var infowindow_strutt = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: '{{name}}'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow_strutt.open(map,marker);
});
var markers = [];
var markers_strutt = [];
var markers_concor = [];
var icon_strutt = {
url: 'http://icons.iconarchive.com/icons/graphicloads/colorful-long-shadow/24/Home-icon.png'
};
var icon_concor = {
url: 'http://icons.iconarchive.com/icons/graphicloads/100-flat/24/home-icon.png'
};
var marker_concor
var marker_strutt
map.addListener('bounds_changed', function() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
$.ajax({
url: '/api/get_marker/',
cache: false,
data: {
'fromlat': southWest.lat(),
'tolat': northEast.lat(),
'fromlng': southWest.lng(),
'tolng': northEast.lng()
},
dataType: 'json',
type: 'GET',
async: false,
success: function (data) {
if (data) {
$.each(data, function (i, item) {
if (item.type = 1) {
var marker_concor = new google.maps.Marker({
position: new google.maps.LatLng(item.lat, item.lng),
icon: icon_concor,
map: map,
draggable: false
});
} else if (item.type = 2) {
var marker_strutt = new google.maps.Marker({
position: new google.maps.LatLng(item.lat, item.lng),
icon: icon_strutt,
map: map,
draggable: false
});
//Create an infoWindow
var infowindow_strutt = new google.maps.InfoWindow();
//set the content of infoWindow (the name)
infowindow_strutt.setContent(item.name);
//add click listner to marker which will open infoWindow
map.addListener(marker_strutt, 'click', function() {
infowindow_strutt.open(marker_strutt); // click on marker opens info window
});
}
markers_concor.push(marker_concor);
markers_strutt.push(marker_strutt);
if (marker_strutt) {
marker_strutt.setMap(map);
}
if (marker_concor) {
marker_concor.setMap(map);
}
});
}
}
});
});
}
jQuery(document).ready(function(e) {
initialize();
});
Where is the issue? Thanks a lot
EDIT: View code
def view_get_marker(request):
id = 24
list_id = []
list_marker = []
list_id.append(id)
# type 1 data
A_list = tab_A.objects.filter(id_struttura=id).filter(lat__gt=request.GET.get('fromlat'), lat__lt=request.GET.get('tolat')).filter(lng__gt=request.GET.get('fromlng'), lng__lt=request.GET.get('tolng'))
for a in A_list:
list_marker.append([a.lat, a.lng, a.name, a.road, a.city, a.id, 1])
list_id.append(a.id)
# type 2 data
B_list = list(tab_B.objects.all().values_list('lat','lng','name','road','city','id').exclude(lng__isnull=True).exclude(id__in=lista_id).filter(lat__gt=request.GET.get('fromlat'), lat__lt=request.GET.get('tolat')).filter(lng__gt=request.GET.get('fromlng'), lng__lt=request.GET.get('tolng')))
for lat, lng, name, road, city, id in B_list:
list_marker.append([lat, lng, name, road, city, id, 2])
if request.is_ajax():
results = []
for row in list_marker:
h_json = {}
h_json['lat'] = row[0]
h_json['lng'] = row[1]
h_json['name'] = unicode(row[2])
h_json['road'] = unicode(row[3])
h_json['city'] = unicode(row[4])
h_json['id'] = row[5]
h_json['type'] = row[6]
results.append(h_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
EDIT 2:
I found the solution. The problem was in the event 'click' declaration. The right way is this:
google.maps.event.addListener(marker_strutt, 'click', (function(marker_strutt, i) {
return function() {
infowindow.setContent('my content');
infowindow.open(map, marker_strutt);
}
})(marker_strutt, i));
In this way I have the popoup!

Related

Get multiple list items by ID in SharePoint List

I am trying to retrieve a list items from a SharePoint list but my issue is that I would like to retrieve the last four items by ID and I don't know how to proceed using JSOM.
Can someone help me whit some CAML code on how to do that?
var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();
//Geting reference to the list
var olist = web.get_lists().getByTitle('Configs');
var oitem = olist.getItemById(1);
//get Title,id,ConfigItem fields
ctx.load(oitem, "Title", "Id", "ConfigItem");
ctx.executeQueryAsync(function () {
alert(oitem.get_item("Title"));
alert(oitem.get_item("ConfigItem"));
}, function (a, b) {
alert(b.get_message());
});
You could use rest api with order by and $top option for this requirement.
/_api/web/lists/getbytitle('chart')/items?$select=ID,Title&$orderby= ID desc&$top=4
Rest api get list items.
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('chart')/items?$select=ID,Title&$orderby= ID desc&$top=4",
type: "GET",
headers:
{
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose"
},
success: function (data) {
for (var i = 0; i < data.d.results.length; i++) {
var item = data.d.results[i];
//to do
}
},
error: function (data) {
console.log(data.responseJSON.error);
}
});
Here is JSOM solution with use of CamlQuery.
var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();
var query = new SP.CamlQuery()
query.set_viewXml("<View><Query><OrderBy><FieldRef Name='ID' Ascending='FALSE' /></OrderBy></Query><RowLimit>4</RowLimit></View>")
var list = web.get_lists().getByTitle('Configs');
var items = list.getItems(query, "ID", "Title", "FirstName", "LastName", "Level", "Grade", "Date");
var dictionary = [];
ctx.load(items);
ctx.executeQueryAsync(function () {
var enumerator = items.getEnumerator();
while (enumerator.moveNext()) {
var item = enumerator.get_current();
dictionary.push({
title: item.get_item("Title"),
firstName: item.get_item("FirstName"),
lastName: item.get_item("LastName"),
level: item.get_item("Level"),
grade: item.get_item("Grade"),
date: item.get_item("Date"),
});
}
}, function (a, b) {
alert(b.get_message());
});

Famo.us Timbre app Scrollview

I'm new to Famo.us and I am trying to expand on the Timbre sample app by adding a scrollview to the PageView where the image would be (in the _createBody function). In other words, I'm trying to add a feed similar to Facebook or Tango, etc. I found two pieces of code online that's been working with (links below). I get no errors on the console log, yet the scrollview won't display, so I'm not sure what I am missing. Your guidance is much appreciated (would also love to know if there is a better way). Finally, this is my first post ever on StackOverflow, so please let me know if I can expose my issue in a better fashion.
Links I have been using for guidance:
StackOverflowFamo.us swipe on scrollview
JSFiddle
/*** AppView.js ***/
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Modifier = require('famous/core/Modifier');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var Easing = require('famous/transitions/Easing');
var Transitionable = require('famous/transitions/Transitionable');
var GenericSync = require('famous/inputs/GenericSync');
var MouseSync = require('famous/inputs/MouseSync');
var TouchSync = require('famous/inputs/TouchSync');
GenericSync.register({'mouse': MouseSync, 'touch': TouchSync});
var PageView = require('views/PageView');
var MenuView = require('views/MenuView');
var StripData = require('data/StripData');
function AppView() {
View.apply(this, arguments);
this.menuToggle = false;
this.pageViewPos = new Transitionable(0);
_createPageView.call(this);
_createMenuView.call(this);
_setListeners.call(this);
_handleSwipe.call(this);
}
AppView.prototype = Object.create(View.prototype);
AppView.prototype.constructor = AppView;
AppView.DEFAULT_OPTIONS = {
openPosition: 276,
transition: {
duration: 300,
curve: 'easeOut'
},
posThreshold: 138,
velThreshold: 0.75
};
function _createPageView() {
this.pageView = new PageView();
this.pageModifier = new Modifier({
transform: function() {
return Transform.translate(this.pageViewPos.get(), 0, 0);
}.bind(this)
});
this._add(this.pageModifier).add(this.pageView);
}
function _createMenuView() {
this.menuView = new MenuView({ stripData: StripData });
var menuModifier = new StateModifier({
transform: Transform.behind
});
this.add(menuModifier).add(this.menuView);
}
function _setListeners() {
this.pageView.on('menuToggle', this.toggleMenu.bind(this));
}
function _handleSwipe() {
var sync = new GenericSync(
['mouse', 'touch'],
{direction : GenericSync.DIRECTION_X}
);
this.pageView.pipe(sync);
sync.on('update', function(data) {
var currentPosition = this.pageViewPos.get();
if(currentPosition === 0 && data.velocity > 0) {
this.menuView.animateStrips();
}
this.pageViewPos.set(Math.max(0, currentPosition + data.delta));
}.bind(this));
sync.on('end', (function(data) {
var velocity = data.velocity;
var position = this.pageViewPos.get();
if(this.pageViewPos.get() > this.options.posThreshold) {
if(velocity < -this.options.velThreshold) {
this.slideLeft();
} else {
this.slideRight();
}
} else {
if(velocity > this.options.velThreshold) {
this.slideRight();
} else {
this.slideLeft();
}
}
}).bind(this));
}
AppView.prototype.toggleMenu = function() {
if(this.menuToggle) {
this.slideLeft();
} else {
this.slideRight();
this.menuView.animateStrips();
}
};
AppView.prototype.slideLeft = function() {
this.pageViewPos.set(0, this.options.transition, function() {
this.menuToggle = false;
}.bind(this));
};
AppView.prototype.slideRight = function() {
this.pageViewPos.set(this.options.openPosition, this.options.transition, function() {
this.menuToggle = true;
}.bind(this));
};
module.exports = AppView;
});
/*** PageView.js ***/
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var HeaderFooter = require('famous/views/HeaderFooterLayout');
var ImageSurface = require('famous/surfaces/ImageSurface');
var Scrollview = require('famous/views/Scrollview');
function PageView() {
View.apply(this, arguments);
_createBacking.call(this);
_createLayout.call(this);
_createHeader.call(this);
_createBody.call(this);
_setListeners.call(this);
}
PageView.prototype = Object.create(View.prototype);
PageView.prototype.constructor = PageView;
PageView.DEFAULT_OPTIONS = {
headerSize: 44
};
function _createBacking() {
var backing = new Surface({
properties: {
backgroundColor: 'black',
boxShadow: '0 0 20px rgba(0,0,0,0.5)'
}
});
this.add(backing);
}
function _createLayout() {
this.layout = new HeaderFooter({
headerSize: this.options.headerSize
});
var layoutModifier = new StateModifier({
transform: Transform.translate(0, 0, 0.1)
});
this.add(layoutModifier).add(this.layout);
}
function _createHeader() {
var backgroundSurface = new Surface({
properties: {
backgroundColor: 'black'
}
});
this.hamburgerSurface = new ImageSurface({
size: [44, 44],
content : 'img/hamburger.png'
});
var searchSurface = new ImageSurface({
size: [232, 44],
content : 'img/search.png'
});
var iconSurface = new ImageSurface({
size: [44, 44],
content : 'img/icon.png'
});
var backgroundModifier = new StateModifier({
transform : Transform.behind
});
var hamburgerModifier = new StateModifier({
origin: [0, 0.5],
align : [0, 0.5]
});
var searchModifier = new StateModifier({
origin: [0.5, 0.5],
align : [0.5, 0.5]
});
var iconModifier = new StateModifier({
origin: [1, 0.5],
align : [1, 0.5]
});
this.layout.header.add(backgroundModifier).add(backgroundSurface);
this.layout.header.add(hamburgerModifier).add(this.hamburgerSurface);
this.layout.header.add(searchModifier).add(searchSurface);
this.layout.header.add(iconModifier).add(iconSurface);
}
function _createBody() {
var surfaces = [];
this.scrollview = new Scrollview();
var temp;
for (var i = 0; i < 30; i++) {
temp = new Surface({
size: [undefined, 80],
content: 'Surface: ' + (i + 1),
properties: {
textAlign: 'left',
lineHeight: '80px',
borderTop: '1px solid #000',
borderBottom: '1px solid #fff',
backgroundColor: '#ffff00',
fontFamily: 'Arial',
backfaceVisibility: 'visible',
paddingLeft: '10px'
}
});
temp.pipe(this.scrollview);
surfaces.push(temp);
}
this.scrollview.sequenceFrom(surfaces);
this.bodyContent = new Surface({
size: [undefined, undefined],
properties: {
backgroundColor: '#f4f4f4'
}
});
this.layout.content.add(this.bodyContent);
}
function _setListeners() {
this.hamburgerSurface.on('click', function() {
this._eventOutput.emit('menuToggle');
}.bind(this));
//this.bodyContent.pipe(this._eventOutput);
this.scrollview.pipe(this._eventOutput);
}
module.exports = PageView;
});
You need to add this.scrollview to your layout.content element on the page. Put this in place of this.bodyContent. layout.content is the node for the content of the page.
//this.layout.content.add(this.bodyContent);
this.layout.content.add(this.scrollview);

Ember calculated property is recalculated without its dependencies changed

I have an calculated property(named userFields) depending on another calculated property(named userList). When the object(it's a view) is initialised, I found the property "userFields" was calculated hundreds of times with "userList" calculated only once, according to the console log. I don't know why does this happened.
Here are my codes:
App.MainServiceInfoApplicationQueueUserGroupSelectView = Ember.View.extend({
templateName: require('templates/main/service/info/applicationqueues/user_group_select'),
userCollapse: false,
groupCollapse: false,
toggleUserCollapse: function() {
myview = this;
this.set('userCollapse', !this.get('userCollapse'));
},
toggleGroupCollapse: function() {
this.set('groupCollapse', !this.get('groupCollapse'));
},
userList: function() {
console.log('calc user list'); // This is printed only once
var list = [];
App.User.find().forEach(function(item) {
list.push(item);
});
return list;
}.property('App.User.find()'),
groupList: function() {
var list = [];
App.Resourcegroup.find().forEach(function(item) {
list.push(item);
});
return list;
}.property('App.Resourcegroup.find()'),
userFields: function() {
console.log('calc user fields'); // This is printed hundreds of times
// Parse value
var parsedValues = [];
try {
var usersFromValue = this.get('value').split(' ')[0].split('/');
for (var i = 0; i < usersFromValue.length; i++)
parsedValues.push(usersFromValue[i]);
} catch (e) {}
var fields = [];
for (var i = 0; i < this.get('userList').length; i++) {
var item = this.get('userList')[i];
fields.push(Ember.Object.create({
viewClass: Ember.Checkbox.extend({
value: false,
checkedBinding: 'value'
}),
displayName: item.get('userName'),
name: item.get('userName'),
value: parsedValues.contains(item.get('userName'))
}));
}
return fields;
}.property('userList'),
groupFields: function() {
// Parse value
var parsedValues = [];
try {
var groupsFromValue = this.get('value').split(' ')[1].split('/');
for (var i = 0; i < groupsFromValue.length; i++)
parsedValues.push(groupsFromValue[i]);
} catch (e) {}
var fields = [];
for (var i = 0; i < this.get('groupList').length; i++) {
var item = this.get('groupList')[i];
fields.push(Ember.Object.create({
viewClass: Ember.Checkbox.extend({
value: false,
checkedBinding: 'value'
}),
displayName: item.get('groupName'),
name: item.get('groupName'),
value: parsedValues.contains(item.get('groupName'))
}));
}
return fields;
}.property('groupList'),
users: function() {
console.log('calc users'); // This is printed as many times as 'calc user fields' was printed
var list = [];
for (var i = 0; i < this.get('userFields').length; i++) {
var theField = this.get('userFields')[i];
if (parseBoolean(theField.get('value')) == true) list.push(theField.get('name'));
}
return list;
}.property('userFields, userFields.#each.value'),
groups: function() {
var list = [];
for (var i = 0; i < this.get('groupFields').length; i++) {
var theField = this.get('groupFields')[i];
if (parseBoolean(theField.get('value')) == true) list.push(theField.get('name'));
}
return list;
}.property('groupFields, groupFields.#each.value'),
usersString: function() {
return this.get('users').join(', ');
}.property('users'),
groupsString: function() {
return this.get('groups').join(', ');
}.property('groups'),
usersValue: function() {
return this.get('users').join('/');
}.property('users'),
groupsValue: function() {
return this.get('groups').join('/');
}.property('groups'),
value: function() {
return this.get('usersValue') + " " + this.get('groupsValue');
}.property('usersValue', 'groupsValue')
});

How to include clickable forms in famo.us surfaces

If I have a surface that hase conent that includes an input. The input doesn't seem to gain focus on click.
Here is how I include my surface.
var ConfigureView = function() {
this.initialize.apply(this, arguments);
};
_.extend(ConfigureView.prototype, {
template: templates['config'],
initialize: function( options ) {
var position = new Transitionable([0, 0]);]
var sync = new GenericSync({
"mouse" : {},
"touch" : {}
});
this.surface = new Surface({
size : [200, 200],
properties : {background : 'red'},
content: this.template()
});
// now surface's events are piped to `MouseSync`, `TouchSync` and `ScrollSync`
this.surface.pipe(sync);
sync.on('update', function(data){
var currentPosition = position.get();
position.set([
currentPosition[0] + data.delta[0],
currentPosition[1] + data.delta[1]
]);
});
this.positionModifier = new Modifier({
transform : function(){
var currentPosition = position.get();
return Transform.translate(currentPosition[0], currentPosition[1], 0);
}
});
var centerModifier = new Modifier({origin : [0.5, 0.5]});
centerModifier.setTransform(Transform.translate(0,0));
},
addTo: function(context) {
context = Engine.createContext()
context.add(this.positionModifier).add(this.surface);
}
});
module.exports = ConfigureView;
What is necessary to make forms act normally with famo.us?
Or do i just need to have an inner surface that has a different listener?
This is templates['config']:
templates["config"] = Handlebars.template({"compiler":[5,">= 2.0.0"],"main":function(depth0,helpers,partials,data) {
return "<input type=\"text\" id=\"fontSize\" >";
},"useData":true});
What displays is an input I just can't seem to focus on it.
UPDATE
The reason I think I couldn't focus was because I wasn't using an inputSurface and the surface event was being pipe away. Using a scrollView I was able to make it work.
var ConfigureView = function() {
this.initialize.apply(this, arguments);
};
_.extend(ConfigureView.prototype, {
template: templates['config'],
initialize: function( options ) {
this.app = options.app;
var position = new Transitionable([0, 0, 1000]);
this.scrollView = new ScrollView();
var surfaces = [];
this.scrollView.sequenceFrom(surfaces);
// create a sync from the registered SYNC_IDs
// here we define default options for `mouse` and `touch` while
// scrolling sensitivity is scaled down
var sync = new GenericSync({
"mouse" : {},
"touch" : {}
});
this.surface = new Surface({
size : [200, 200],
properties : {background : 'red'},
content: this.template()
});
surfaces.push(this.surface);
this.offsetMod = new Modifier({ origin: [0.2,0,2]});
this.inner = new Surface({
size : [100, 100],
properties : {background : 'gray'},
content: this.template()
});
surfaces.push(this.inner);
// now surface's events are piped to `MouseSync`, `TouchSync` and `ScrollSync`
this.surface.pipe(sync);
this.inputsFontSize = new InputSurface({
classes: ['login-form'],
content: '',
size: [300, 40],
placeholder:'email',
properties: {
autofocus:'autofocus',
maxLength:'5',
textAlign: 'left'
}
});
sync.on('update', function(data){
var currentPosition = position.get();
position.set([
currentPosition[0] + data.delta[0],
currentPosition[1] + data.delta[1]
]);
});
this.positionModifier = new Modifier({
transform : function(){
var currentPosition = position.get();
return Transform.translate(currentPosition[0], currentPosition[1], 0);
}
});
var centerModifier = new Modifier({origin : [0.5, 0.5]});
centerModifier.setTransform(Transform.translate(0,0));//, y, z))
},
addTo: function(context) {
context = Engine.createContext();
context.add(this.positionModifier).add(this.scrollView);
}
});
module.exports = ConfigureView;

Ember-table integration with Ember-model / Ember-data

I am trying to link ember-models to the ember-table to pull paginated records from the server and add them to the table when scrolling down.
I can get it working by just requesting my api url with page number like in the ajax example on http://addepar.github.io/ember-table/ but i cant figure out how to integrate it with ember-model to create and ember objects and then add them to the table.
Here is my code to just make an ajax request and add to table. Can anyone tell me how i can change this to use ember-model / ember-data instead.
App.TableAjaxExample = Ember.Namespace.create()
App.TableAjaxExample.LazyDataSource = Ember.ArrayProxy.extend
createGithubEvent: (row, event) ->
row.set 'id', event.id
row.set 'name', event.name
row.set 'isLoaded', yes
requestGithubEvent: (page) ->
content = #get 'content'
start = (page - 1) * 30
end = start + 30
per_page = 40
# something like this ???
#App.Detail.find(type: 'companies', page: page, per_page: per_page).on 'didLoad', ->
url = "http:/myurl.dev/admin/details.json?type=companies&page=#{page}&per_page=30"
Ember.$.getJSON url, (json) =>
json.details.forEach (event, index) =>
row = content[start + index]
#createGithubEvent row, event
[start...end].forEach (index) ->
content[index] = Ember.Object.create eventId: index, isLoaded: no
objectAt: (index) ->
content = #get 'content'
#if index is content.get('length') - 1
# content.pushObjects(new Array(30))
row = content[index]
return row if row and not row.get('error')
#requestGithubEvent Math.floor(index / 30 + 1)
content[index]
App.TableAjaxExample.TableController =
Ember.Table.TableController.extend
hasHeader: yes
hasFooter: no
numFixedColumns: 0
numRows: 21054
rowHeight: 35
columns: Ember.computed ->
columnNames = ['id', 'name']
columns = columnNames.map (key, index) ->
Ember.Table.ColumnDefinition.create
columnWidth: 150
headerCellName: key.w()
contentPath: key
columns
.property()
content: Ember.computed ->
App.TableAjaxExample.LazyDataSource.create
content: new Array(#get('numRows'))
.property 'numRows'
Is the possible or does this slow it down to much?
Thanks for the help.
Rick
Here's a JSBin that I got working with Ember Data and the RESTAdapter: http://jsbin.com/eVOgUrE/3/edit
It works very similarly to the AJAX loading example, but uses Ember Data to load the data. I created a RowProxy object that is returned immediately to the Ember Table so that it can render a row. After Ember Data loads a page full of data it sets the object property on the RowProxy which updates the view.
window.App = Ember.Application.create();
// The main model that will be loaded into Ember Table
App.Gallery = DS.Model.extend({
name: DS.attr('string'),
smallUrl: DS.attr('string')
});
// This is a temporary buffer object that sits between
// Ember Table and the model object (Gallery, in this case).
App.RowProxy = Ember.Object.extend({
object:null,
getObjectProperty : function(prop){
var obj = this.get('object');
if(obj){ console.log(prop + " : " + obj.get(prop)); }
return obj ? obj.get(prop) : 'loading...';
},
isLoaded : function(){ return !!this.get('object'); }.property('object'),
name : function(){ return this.getObjectProperty('name'); }.property('object.name'),
id : function(){ return this.getObjectProperty('id'); }.property('object.id'),
smallUrl : function(){ return this.getObjectProperty('smallUrl'); }.property('object.smallUrl')
});
App.ApplicationController = Ember.Controller.extend({
tableController: Ember.computed(function() {
return Ember.get('App.TableAjaxExample.TableController').create({
// We need to pass in the store so that the table can use it
store : this.get('store')
});
})
});
App.TableAjaxExample = Ember.Namespace.create();
App.TableAjaxExample.ImageTableCell = Ember.Table.TableCell.extend({
templateName: 'img-table-cell',
classNames: 'img-table-cell'
});
App.TableAjaxExample.LazyDataSource = Ember.ArrayProxy.extend({
requestPage : function(page){
var content, end, start, url, _i, _results,
_this = this;
content = this.get('content');
start = (page - 1) * 3;
end = start + 3;
// Find galleries and then update the RowProxy to hold a gallery as 'object'
this.get('store').find('gallery',{page_size:3,page:page}).then(function(galleries){
return galleries.forEach(function(gallery, index) {
var position = start + index;
content[position].set('object',gallery);
});
});
// Fill the 'content' array with RowProxy objects
// Taken from the 'requestGithubEvent' method of the original example
return (function() {
_results = [];
for (var _i = start; start <= end ? _i < end : _i > end; start <= end ? _i++ : _i--){ _results.push(_i); }
return _results;
}).apply(this).forEach(function(index) {
return content[index] = App.RowProxy.create({
index: index
});
});
},
objectAt: function(index) {
var content, row;
content = this.get('content');
row = content[index];
if (row && !row.get('error')) {
return row;
}
this.requestPage(Math.floor(index / 3 + 1));
return content[index];
}
});
App.TableAjaxExample.TableController = Ember.Table.TableController.extend({
hasHeader: true,
hasFooter: false,
numFixedColumns: 0,
numRows: 19,
rowHeight: 35,
columns: Ember.computed(function() {
var avatar, columnNames, columns;
avatar = Ember.Table.ColumnDefinition.create({
columnWidth: 80,
headerCellName: 'smallUrl',
tableCellViewClass: 'App.TableAjaxExample.ImageTableCell',
contentPath: 'smallUrl'
});
columnNames = ['id', 'name'];
columns = columnNames.map(function(key, index) {
return Ember.Table.ColumnDefinition.create({
columnWidth: 150,
headerCellName: key.w(),
contentPath: key
});
});
columns.unshift(avatar);
return columns;
}).property(),
content: Ember.computed(function() {
return App.TableAjaxExample.LazyDataSource.create({
content: new Array(this.get('numRows')),
store : this.get('store')
});
}).property('numRows')
});
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://files.cloudhdr.com/api/v1/public',
// This is here to use underscores in API params
pathForType: function(type) {
var underscored = Ember.String.underscore(type);
return Ember.String.pluralize(underscored);
}
});
// Everything below is all here to use underscores in API params.
// You may or may not need this.
DS.RESTSerializer.reopen({
modelTypeFromRoot: function(root) {
console.log("modelTypeFromRoot " + root);
var camelized = Ember.String.camelize(root);
return Ember.String.singularize(camelized);
}
});
App.ApplicationSerializer = DS.RESTSerializer.extend({
normalize: function(type, hash, property) {
var normalized = {}, normalizedProp;
for (var prop in hash) {
if (prop.substr(-3) === '_id') {
// belongsTo relationships
normalizedProp = prop.slice(0, -3);
} else if (prop.substr(-4) === '_ids') {
// hasMany relationship
normalizedProp = Ember.String.pluralize(prop.slice(0, -4));
} else {
// regualarAttribute
normalizedProp = prop;
}
normalizedProp = Ember.String.camelize(normalizedProp);
normalized[normalizedProp] = hash[prop];
}
return this._super(type, normalized, property);
}
});