Load JSON file to Backbone collection - json

Hi I'm looking for proper solution to load JSON to Backbone collection. I saw a lot of post with this problem, but I still don't understand how to do it correctly.
For example, Could You explain me please why this project doesn't work?
http://blog.joelberghoff.com/2012/07/22/backbone-js-tutorial-part-1/
Edit:
When I look at the results using Firebug, it shows me an empty object, collection is empty.
Why?
EDIT:
hmmm, still doesn't work :/ Now I don't see anything in firebug and one the page. :(
$(function() {
var Profile = Backbone.Model.extend();
var ProfileList = Backbone.Collection.extend({
model: Profile,
url: 'profiles.json'
});
var ProfileView = Backbone.View.extend({
el: "#profiles",
template: _.template($('#profileTemplate').html()),
render: function(eventName) {
_.each(this.model.models, function(profile){
var profileTemplate = this.template(profile.toJSON());
$(this.el).append(profileTemplate);
}, this);
return this;
}
});
var profiles = new ProfileList();
var profilesView = new ProfileView({model: profiles});
var profiles = new ProfileList();
profiles.fetch();
profiles.bind('reset', function () {
console.log(profiles);
profilesView.render();
});
});

Your fetch call is asynchronous, as I'm sure it's written in the tutorial. So when you're doing the console.log, your collection is still empty.
Farther in the tutorial..:
var profiles = new ProfileList();
profiles.fetch({reset: true});
profiles.bind('reset', function () { console.log(profiles); });
This should work.

Related

Button for markupCore extension not showing in dockingpanel

I have followed Philippe Leefsma's tutorial on how to implement the markup tool, but without any luck. Link here: http://adndevblog.typepad.com/cloud_and_mobile/2016/02/playing-with-the-new-view-data-markup-api.html
and here: https://developer.api.autodesk.com/viewingservice/v1/viewers/docs/tutorial-feature_markup.html
I get errors that I need to include requireJS, but I don't want to use it. So instead I used this script in my html file:
<script src="https://autodeskviewer.com/viewers/2.2/extensions/MarkupsCore.js">
I don't know if this is the right way to go? I get no errors in the console, but the markup button doesn't show up in the dockingpanel.
This is my code for loading the extension in the viewer:
viewerApp = null;
function initializeViewer(containerId, urn, params) {
function getToken(url) {
return new Promise(function (resolve, reject) {
$.get(url, function (response) {
resolve(response.access_token);
});
});
}
var initOptions = {
documentId: 'urn:' + urn,
env: 'AutodeskProduction',
getAccessToken: function (onGetAccessToken) {
getToken(params.gettokenurl).then(function (val) {
var accessToken = val;
var expireTimeSeconds = 60 * 30;
onGetAccessToken(accessToken, expireTimeSeconds);
});
}
}
function onDocumentLoaded(doc) {
var rootItem = doc.getRootItem();
// Grab all 3D items
var geometryItems3d =
Autodesk.Viewing.Document.getSubItemsWithProperties(
rootItem, { 'type': 'geometry', 'role': '3d' }, true);
// Grab all 2D items
var geometryItems2d =
Autodesk.Viewing.Document.getSubItemsWithProperties(
rootItem, { 'type': 'geometry', 'role': '2d' }, true);
// Pick the first 3D item otherwise first 2D item
var selectedItem = (geometryItems3d.length ?
geometryItems3d[0] :
geometryItems2d[0]);
var domContainer = document.getElementById('viewerContainer');
var config = { extensions: ["Autodesk.Viewing.MarkupsCore"] };
// GUI Version: viewer with controls
var viewer = new Autodesk.Viewing.Private.GuiViewer3D(domContainer, config);
viewer.loadExtension("Autodesk.Viewing.MarkupsCore");
viewer.initialize();
viewer.loadModel(doc.getViewablePath(selectedItem));
var extension = viewer.getExtension("Autodesk.Viewing.MarkupsCore");
viewerApp = viewer;
}
function onEnvInitialized() {
Autodesk.Viewing.Document.load(
initOptions.documentId,
function (doc) {
onDocumentLoaded(doc);
},
function (errCode) {
onLoadError(errCode);
})
}
function onLoadError(errCode) {
console.log('Error loading document: ' + errCode);
}
Autodesk.Viewing.Initializer(
initOptions,
function () {
onEnvInitialized()
})
}
Any help is highly appreciated!
Unfortunately there has been a few changes to the API since I wrote that blog post. The MarkupCore.js is now included in the viewer3D.js source, so you don't need to reference any extra file or use requireJS if you use the latest version of the viewer API.
Keep in mind that this is an API-only feature, so even after loading the markup extension, you won't get any UI out of the box. You have to implemented it yourself, for example create a dialog with buttons that may eventually create markups by calling the API.
Some of the code from my blog post may still be valid and give you an idea about what you need to do.
Hope that helps.

Data from chrome storage

How do i retrieve data from chrome.storage.sync.set and place it in new variable?
var marke = 'value1';
chrome.storage.sync.set({myKey: marke}, function() {
alert('saved');
});
chrome.storage.sync.get('first', function(e) {
console.log(e.first)
});
I can console.log it, but don't know how to place it in different variable or use it elsewhere

Using Spotify webAPI to play random album of artist (ID)

here is my "little" project, as I am not a developer myself please don't blame me for my stupid questions.
I want to create a "audio book machine".
I want to use a Website, that shows several Artists of audiobooks. If I click on one artist, a random audiobook of the clicked artist should be played.
I had a look at this code example: http://jsfiddle.net/qlmhuge/t7a1sh4u/
// find template and compile it
var templateSource = document.getElementById('results-template').innerHTML,
template = Handlebars.compile(templateSource),
resultsPlaceholder = document.getElementById('results'),
playingCssClass = 'playing',
audioObject = null;
var fetchTracks = function (albumId, callback) {
$.ajax({
url: 'https://api.spotify.com/v1/artists/61qDotnjM0jnY5lkfOP7ve/albums/',
success: function (response) {
callback(response);
}
});
};
var searchAlbums = function (query) {
$.ajax({
url: 'https://api.spotify.com/v1/search',
data: {
q: 'artist:' + query,
type: 'album',
market: "DE"
},
success: function (response) {
resultsPlaceholder.innerHTML = template(response);
}
});
};
results.addEventListener('click', function(e) {
var target = e.target;
if (target !== null && target.classList.contains('cover')) {
if (target.classList.contains(playingCssClass)) {
audioObject.pause();
} else {
if (audioObject) {
audioObject.pause();
}
fetchTracks(target.getAttribute('data-album-id'), function(data) {
audioObject = new Audio(data.tracks.items[0].preview_url);
audioObject.play();
target.classList.add(playingCssClass);
audioObject.addEventListener('ended', function() {
target.classList.remove(playingCssClass);
});
audioObject.addEventListener('pause', function() {
target.classList.remove(playingCssClass);
});
});
}
}
});
searchAlbums('TKKG');
but I cannot figure out how to change it to play a random album by one artist.
The artist will be defindes by the spotify ID so that the artist ist the correct one.
Can someone help me out with my problem? What else info is needed to complete my goal?
I would be very thankful if one can give me a hint, or whatever, to get to the right direction.
Best regards,
goeste
You have to modify your fetchTracks function here:
var fetchTracks = function (albumId, callback) {
$.ajax({
url: 'https://api.spotify.com/v1/albums/' + albumId,
success: function (response) {
callback(response);
}
});
};
jsFiddle link
I got a little closer to the finish line... well, I guess:
I found the following on GitHub:
var SpotifyWebApi = require('spotify-web-api-node');
var spotifyApi = new SpotifyWebApi();
// credentials are optional
// var spotifyApi = new SpotifyWebApi({
// clientId : '',
// clientSecret : '',
// redirectUri : ''
// });
// Get albums by a certain artist
spotifyApi.getArtistAlbums('3meJIgRw7YleJrmbpbJK6S')
.then(function(data) {
console.log('Artist albums', data.body);
}, function(err) {
console.error(err);
});
However, I only get 20 albums out of 35. I need to increase the limit. The max limit is 50, as I read on the developer site of Spotify. As I only need to get one out of the 35 albums (randomly), how can I implement the randomize function and also play function in order to work?
I am still figuring out how to create a link from the results to show on a website with node.js.
Best regards, and thank you in advance for any assistance/help!
-goeste

backbone.js fetch json success will not hit

i use fetch from backbone.js to load a json model but success will not hit.
var DialogModel = Backbone.Model.extend({
url : function() {
return '/messages/getDialog';
},
parse : function(res) {
return res.dialog;
}
});
var DialogView = Backbone.View.extend({
el: $("#page"),
initialize: function() {
var onDataHandler = function() {
this.render();
};
this.model = new DialogModel();
this.model.fetch({ success : onDataHandler});
},
render: function(){
var data = {
dialogModel : this.model
};
var form = new Backbone.Form({
model: data
});
$(this.el).html(form.render().el);
}
});
What happens now:
DialogView initialize is called.
this.model.fetch is called but the onDataHandler function will not be hit if success.
/messages/getDialog throws a json file back.
The json file is loading well as i can see in the network browser.
Thanks for your help!
Oleg
The problem you're having is due to a typical JS gotcha and not related to Backbone itself. Try
var that = this;
this.model.fetch({
success : function () {
that.render();
}
});
The way you're currently passing onDataHandler is problematic as it will cause this to refer to the global object instead of the DialogView, when the function is called.
This fiddle demonstrates the problematic version vs one that works.
(You may also want to take a look at JS strict mode which can shield you from this type of errors.)
Even better is to listen for an event:
this.model.on("sync", this.render).fetch();
I ran across this question while looking for something else, but the currently accepted answer drives me nuts. There's no good reason to be sprinkling this and that all over your code. Backbone (underscore) includes a context parameter that you can bind to.
that = this makes no sense. If you must implement obsolete 2007-era Crockford patterns, then say var self = this. Saying that = this is like saying left = right. Everyone Stop.

Combining AJAX/JSON call with iScroll

I am making a list form my JQM site from JSON data and are having no trouble with this. Now I want to add iScroll to the scene and if I use static list it works just fine, but when I get the list from JSON it won't fetch how many li I have and I can not scroll down to the bottom if I have lets say 20 li. I dont know how to combine my javascript so here is what i got so far [EDIT]:
var myScroll;
$(document).on('pageshow', function (){
var userid=1,
dataUrl = 'http://duefmun.dk/html5data/playermenu.php?callback=?&userid=' + userid,
dataCallback = function (data) {
var content = [];
$.each(data, function (i, val) {
content.push(val.list);
});
$('#games').html(content.join('')).listview('refresh');
},
fetchData = function () {
myScroll = new iScroll('wrapper');
if (myScroll.isReady()){
$.getJSON(dataUrl, dataCallback);
}
};
fetchData();
setInterval(fetchData, 20000);
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', function () { setTimeout(loaded, 200); }, false);
});
Hope this makes sense and any help is appreciated :-)
EDIT: I have edited the post with something I think should be right but it is still not working? Please help :-/
My suggestion is that you should create iScroll after you get your data. So, your code should be:
...
fetchData = function () {
if (myScroll.isReady()){
$.getJSON(dataUrl, dataCallback);
}
};
fetchData();
setInterval(fetchData, 20000);
myScroll = new iScroll('wrapper');
...