I'm still new at Polymer and I'm slowly learning how to use Polymer by modifiying the examples that Google provided.
But I'm encountering a bit of an issue.
I have a Array in Javascript:
var dash = [{"uid": 1,
"text" : "It's a TOWN!",
"username" : "Sam112",
"avatar" : "../ToolKit/images/avatar-01.svg",
"favorite": false,
"num" : "Standard"}];
function addto ()
{
dash.push({"uid": 2,
"text" : "It's a BABY!",
"username" : "Pete223",
"avatar" : "../ToolKit/images/avatar-01.svg",
"favorite": false,
"num" : "Standard"});
}
And I want to put this data in the 'post-service' template file:
<script>
Polymer('post-service',
{
created: function()
{
this.posts = dash;
},
postsLoaded: function()
{
this.posts = this.$.ajax.response.slice(0);
},
setFavorite: function(uid, isFavorite)
{
console.log('Favorite changed: ' + uid + ", now: " + isFavorite);
}
});
</script>
So i called the addto() function and then I loaded the index.html Polymer file and i expected to load data from the Array...
But It loads the Array, but the added object ( from addto() ), doesn't load.
It apparently loads from the original array but not the new entry from the addto() function.
Is there a way to make 'post-service' load an array when it changes? Thanks again!
I think this is not working because dash is only assigned to this.posts in the created handler, so typically on construction of the polymer element. If you call addTo afterwards, it will change dash, but dash will never be assigned to this.posts again.
Maybe add the addTo function to the element itself? Like:
Polymer('post-service',
{
created: function()
{
this.posts = dash;
},
addTo: function(arr)
{
this.posts.push (arr)
},
postsLoaded: function()
{
this.posts = this.$.ajax.response.slice(0);
},
setFavorite: function(uid, isFavorite)
{
console.log('Favorite changed: ' + uid + ", now: " + isFavorite);
}
});
</script>
Thanks kroonwijk!
I eventually gave up and I just used local-storage and JSON's stringify and parse to transfer between the Polymer element and my Javascript Data.
localStorage["names"] = JSON.stringify(dash);
And on the Polymer Side...
Polymer('post-service',
{
created: function()
{
this.posts = JSON.parse(localStorage["names"]);
},
postsLoaded: function()
{
this.posts = this.$.ajax.response.slice(0);
},
setFavorite: function(uid, isFavorite)
{
console.log('Favorite changed: ' + uid + ", now: " + isFavorite);
}
});
Much easier, sorry IE 7 and lower...
Related
I read the doc here : https://documentation.onesignal.com/docs/cordova-sdk but it's totally not clear !
I try severals test nothing, I event test to get the title but still nothing
document.addEventListener('deviceready', function () {
// Enable to debug issues.
// window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});
var notificationOpenedCallback = function(jsonData) {
alert('notificationCallback: ' + JSON.stringify(jsonData)); => json data
alert('Title : '+ JSON.stringify(jsonData.payload.title)); => nothing
alert('Title2 : '+ jsonData.payload.title); => nothing
alert('Additional data: '+ jsonData.payload.additionalData); => nothing
};
window.plugins.OneSignal
.startInit("MY_ID")
.handleNotificationOpened(notificationOpenedCallback)
.endInit();
}, false);
How to retrieve this data..
Thanks
After multiple debugs on my app, I finally found the application. The JSON structure of jsonData is :
jsonData
notification: {
payload: {
title: "YOUR_TITLE",
body: "BODY",
additionalData: {
"YOUR_KEY" : "YOUR_VALUE"
},
So to retrieve your data :
JSON.stringify(jsonData.notification.payload.additionalData.<YOUR_KEY>)
Instead of jsonData.payload try with jsonData.OSNotificationPayload
Ex: to access title
jsonData.OSNotificationPayload.title
I am trying to pause the rendering of an a-entity with a custom function that utilizes the .pause() method. Here is my Aframe component:
<body style="margin : 0px; overflow: hidden;">
<script>
AFRAME.registerComponent('intro', {
schema: {
array: { type: "array", default: ["Hi! I'm Ducky and welcome to", "Black", "Duck"] }
},
init: function() {
const self = this;
pauseTextRender(self);
}
function pauseTextRender(component) {
component.pause();
}
});
</script>
</body>
This is bare minimum. When I check the console I get the error Uncaught SyntaxError: Unexpected token function. I'm not too familiar with Javascript but how can I make an acceptable function for the Aframe class?
Your Javascript Syntax is incorrect. Which is why you are getting the syntax error. Try doing something like this:
,
/**
* Setup fade-in + fade-out.
*/
setupFadeAnimation: function() {
var data = this.data;
var targetEl = this.data.target;
// Only set up once.
if (targetEl.dataset.setImageFadeSetup) {
return;
}
targetEl.dataset.setImageFadeSetup = true;
// Create animation.
targetEl.setAttribute('animation__fade', {
property: 'material.color',
startEvents: 'set-image-fade',
dir: 'alternate',
dur: 500,
from: '#FFF',
to: '#000'
});
}
Notice the comma which would be after your init function and the way I declare the function setupFadeAnimation.
To answer the question - unexpected token: function is because your pauseTextRender declaration is incorrect in this context. It would be absolutely correct in a different context but, for this one, you need to do :
pauseTextToRender: function(component){
component.pause();
}
So your entire registration would look like :
AFRAME.registerComponent('intro', {
schema: {
array: {
type: "array",
default: ["Hi! I'm Ducky and welcome to", "Black", "Duck"]
}
},
init: function() {
const self = this;
pauseTextRender(self);
},
pauseTextRender: function(component) {
component.pause();
}
});
(Note the comma after the init declaration as well)
This is because inside an object you have pairs like so :
{
name: "value",
anotherName: "another value"
}
...and what was happening for you was that you were giving the value function pauseTextRender(component){ ...etc... } without giving the name, and not separating your declarations with a comma.
Hope that helps!
Pretty new to Backbone, so please mind my ignorance...
I have a simple GallereyModel:
var GalleryModel = Backbone.Model.extend({
defaults : {
id: "",
width: ""
},
url : ""
});
When the model is updated, the function galleryModelUpdate is called
var GalleryView = Backbone.View.extend({
initialize: function () {
this.listenTo(this.model, "change", this.galleryModelUpdate);
},
galleryModelUpdate: function(){
console.log("updated gallery model"+this.model.get("id");
if (this.model.get("url")){
console.log("fetching " + this.model.get("url")); // this line prints with the correct url
this.model.fetch({ // this line gives error
success: function(){
console.log("fetched succesfully!");
}
});
}
}
});
I am printing the value of url on the model before fetch is called, so not sure why is it throwing the "url" undefined error?
Many thanks for your help in advance
Either the url or the urlRoot model properties needs to be defined in order for the model to fetch.
You can set your model url to point to the url data attribute:
Backbone.Model.extend({
url: function () {
return this.get('url');
}
});
I have written a series of Parse Promises and am now getting error 141 when I make a request to this cloud code function. I have tried placing success: / error: all over the function where I think they belong based on the Parse DOCS.
Request
{
"projectDescription": "Testing saveProject",
"projectTitle": "This is only a test, in the event of a real post this will have an actual description",
"isEmailEnabled": true,
"shareEmails": [
"max#gmail.com",
"nat#gmail.com",
"noob#gmail.com"
],
"userId": "sLmOf4fZFL"
}
Parse.Cloud.define("saveProject", function(request, response) {
var emails = request.params.shareEmails;
var user = request.params.userId;
var projectDescription = request.params.projectDescription;
var projectTitle = request.params.projectTitle;
var emailStatus = request.params.isEmailEnabled;
var ProjectClass = Parse.Object.extend("Project");
var EmailsClass = Parse.Object.extend("Email");
var EmailsClassAssignment = Parse.Object.extend("EmailAssignment");
var project = new ProjectClass();
var projectO;
project.set("title", projectTitle);
project.set("createdBy", {
"__type": "Pointer",
"className": "_User",
"objectId": user
});
project.set("description", projectDescription);
project.set("status", true);
project.set("emailShareEnabled", emailStatus);
project.save().then(function(results) {
projectO = results;
console.log(projectO);
return Parse.Promise.when(emails.map(function(emailAddress) {
var email = new EmailsClass();
email.set("address", emailAddress);
return email.save();
}));
}).then(function() {
return Parse.Promise.when(emails.map(function(emailQuery) {
var queryEmail = new Parse.Query("Email");
queryEmail.equalTo("address", emailQuery);
return queryEmail.find().then(function(results) {
var emailJSON = results[0].toJSON();
var emailObjectId = emailJSON.objectId;
var projectJSON = projectO.toJSON();
var projectId = projectJSON.objectId;
var assignment = new EmailsClassAssignment();
assignment.set("createdBy", {
"__type": "Pointer",
"className": "_User",
"objectId": user
});
assignment.set("email", {
"__type": "Pointer",
"className": "Email",
"objectId": emailObjectId
});
assignment.set("project", {
"__type": "Pointer",
"className": "Project",
"objectId": projectId
});
assignment.save(null, {
success: function() {
console.log("Successfully saved project");
},
error: function(error) {
console.log("There was an error saving" + error.message);
}
});
});
}));
}).then( function() {
response.success();
});
});
The basic ideas look okay, but the code is kind of a jumble of callback parameters and promises. I took the liberty of refactoring into simpler, promise-returning logical chunks so we could see what's going on.
You highlighted the .map functions in the post. Not sure what the issue was there, so the code I suggest uses underscorejs, which can be easily included in the cloud as follows:
var _ = require('underscore');
First, return a promise to save a "project" given most of the params to your cloud function:
function createProject(params) {
var ProjectClass = Parse.Object.extend("Project");
var project = new ProjectClass();
var emails = request.params.shareEmails;
var user = request.params.userId;
var projectDescription = request.params.projectDescription;
var projectTitle = request.params.projectTitle;
var emailStatus = request.params.isEmailEnabled;
project.set("title", projectTitle);
project.set("createdBy", {
"__type": "Pointer",
"className": "_User",
"objectId": user
});
project.set("description", projectDescription);
project.set("status", true);
project.set("emailShareEnabled", emailStatus);
return project.save();
}
Next, create "Email"'s (which are objects) given an array of email address strings. (You would do well to more carefully distinguish the objects and the strings in your naming, but I tried to hew to original nomenclature in the code)
function createEmails(emails) {
var EmailsClass = Parse.Object.extend("Email");
var toSave = _.map(emails, function(emailAddress) {
var email = new EmailsClass();
email.set("address", emailAddress);
return email;
});
// like the when() function, but (possibly) fewer requests
return Parse.Object.saveAll(toSave);
}
This is where the original code took a turn for the worse. In it, the code just finished creating the Email objects, then for some reason, it attempts to query those objects. But we have them in hand already, on the fulfullment of the promises to save.
The method below, takes already built email objects (named pedantically, to emphasize that they are objects) and other ingredients to an "EmailClassAssignment". Notice how we can assign pointers directly with objects when we have a PFObject in hand:
function createEmailClassAssignments(emailObjects, project, userId) {
var EmailsClassAssignment = Parse.Object.extend("EmailAssignment");
var toSave = _.map(emailObjects, function(emailObject) {
var assignment = new EmailsClassAssignment();
// the real objects can be used as parameters to set for pointer columns
assignment.set("email", emailObject);
assignment.set("project", project);
// we only have the userId, not a user object, so we can either query
// for the user or take the shortcut that you've been taking
project.set("createdBy", {
"__type": "Pointer",
"className": "_User",
"objectId": user
});
return assignment;
});
return Parse.Object.saveAll(toSave);
}
With all that done, the cloud function becomes more legible:
Parse.Cloud.define("saveProject", function(request, response) {
var project;
createProject(params).then(function(result) {
project = result;
return createEmails(request.params.shareEmails);
}).then(function(emailObjects) {
return createEmailClassAssignments(emailObjects, project, request.params.userId);
}).then(function() {
console.log("Successfully saved project");
// I took the liberty of returning the new project to the caller
response.success(project);
}, function(error) {
console.log("There was an error saving" + error.message);
resoonse.error(error);
});
});
CAUTION: obviously, there's no way for me to test any of the foregoing. I strongly urge you to test the functions yourself, preferably individually before expecting the combination to work. Hopefully, the refactor demonstrates a cleaner way to use promises and a reasonable decomposition of parts to test and use individually.
From the looks of your code, you simply need to add a return in front of assignment.save() as you aren't waiting for that to finish otherwise.
Lastly you should add an error catcher at the very end:
.then(null, function(error) {
console.log(error);
response.error(error);
});
I am trying to set parent for features which I copied for particular MMF, but parent is getting set for only last feature.
Below line of code to set the parent
Record is new feature object
_newParent is the MMF object, where I am doing wrong
record.set("Parent", _newParent.get("_ref")),
Need help please.Any suggestions?
Whole is method is this
_genericInnerCopy: function(_childObj) {
that = this;
model = that.model;
var record = Ext.create(model, {
Name: _childObj.get('Name'),
//Parent: _newParent.get("_ref");,
});
record.save({
callback: function(result, operation) {
if(operation.wasSuccessful()) {
console.log("Done");
//that._copyChild();
} else {
console.log("error");
}
}
})
that._all_pis.push(record);
console.log("all pis values", that._all_pis);
var store = Ext.create('Rally.data.custom.Store', {
data: that._all_pis,
listeners: {
load: that._updateAll,
scope: that
},
});
//console.log("record values", that._all_pis);
},
_updateAll: function(store,data) {
console.log("store values", store);
console.log("data values", data);
Rally.data.BulkRecordUpdater.updateRecords({
records: data,
propertiesToUpdate: {
Parent: _newParent.get("_ref")
},
success: function(readOnlyRecords){
//all updates finished, except for given read only records
},
scope: that
});
//that._createNewItems(that._all_pis);
},
The problem in your original question was that your code wasnt spitting out the errors in the callback. To see the errors you can console.log(operation.getError()) or console.log(operation) and inspect the output.