Assigning value to variables in polymer - polymer

Polymer doesn't bind data if we assign value to polymer multiple times.
For example:
Polymer({
is: "g-feed",
properties: {
event: String
},
ready: ()=> {
var self = this;
self.news = [];
var nws = [];
nws.push({nm:'One'});
nws.push({nm:'Two'});
self.news = nws;
nws.push({nm:'One1'});
nws.push({nm:'Twoa'});
self.news = nws;
console.log(self.news);
}
});
Here the news array would only hold the values "one" and "two" rendered on the webpage.
Can you please tell me why this happens and how to overcome this. Also, how to work with consistantly changing data in polymer.
Thanks.

Related

Function inside a Function not calling in React Native

I am new to react-native and calling a function inside a fucntion.
I have done as below so far :
Step 1 : Created a function _snapshotToArray to convert the firebase snapshot to Arrray.
_snapshotToArray(snapshot) {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
});
return returnArr;
}
Step 2 : Created another function as below and calling _snapshotToArray inside it.
_readUserDataFromFirebaseConsole() {//once and on
firebase.database().ref('Users/').on('value', function (snapshot) {
console.log(this._snapshotToArray(snapshot));
Toast.show(this._snapshotToArray(snapshot),Toast.LONG);
});
}
Talking about this call :
console.log(this._snapshotToArray(snapshot));
When I press CTRL+CLick, it not letting me to navigate to body of the fuction _snapshotToArray.
In Device am getting below error :
_snapshotToArray is not defined
What might be the issue ?
I'm not at my PC right now, so I cannot test it, but from looking at your code, you need to use a different function notation to allow the varibale access of/from parent methods and parent class.
_snapshotToArray = snapshot => {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
});
return returnArr;
}
and
_readUserDataFromFirebaseConsole = () => {
firebase.database().ref('Users/').on('value', snapshot => {
console.log(this._snapshotToArray(snapshot));
Toast.show(this._snapshotToArray(snapshot),Toast.LONG);
});
}

Can not stub private element in WCT

Using Polymer 1 and Web component tester... testing in shady dom on chrome.
In WCT, trying to stub spToast.display() with stub('sp-toast', { display: ()=> {} }); but I get error with Attempted to wrap undefined property display as function.... what I am doing wrong?
The reason why I am trying to stub it is because I get spToast.display is not a function when the test runs the code base.
original code:
showAgeWarning: function() {
var spApp = Polymer.dom(document).querySelector('sp-app');
var spToast = Polymer.dom(spApp.root).querySelector('sp-toast');
var msg = "foo"
spToast.display('information', msg);
},
test code:
<test-fixture id="sp-veteran">
<template>
<h2>edit veteran</h2>
<sp-app>
<sp-toast></sp-toast>
<sp-veteran>
</sp-veteran>
</sp-app>
</template>
</test-fixture>
setup(function() {
replace('sp-app').with('fake-sp-app');
replace('sp-ajax').with('fake-sp-ajax');
stub('sp-value-dropdown', { setInvalidState: (state)=> {} });
myEl = fixture('sp-veteran');
});
test('it should validate the veteran', function() {
var spApp = Polymer.dom(myEl.root).querySelector('sp-app');
var spToast = Polymer.dom(spApp.root).querySelector('sp-toast');
sinon.stub(spToast, 'display');
When you get Attempted to wrap undefined property display as function it means that it can't replace a method that doesn't exist (yet).
If you actually get a value for var spToast = Polymer.dom(spApp.root).querySelector('sp-toast') in your test, and nothing about your test is going to give display a value, you could just set it, a la spToast.display = function() {}; then you should be able to set a spy on it or what have you as needed.
Put it all together and you could have
test('it should validate the veteran', function() {
var spApp = Polymer.dom(myEl.root).querySelector('sp-app');
var spToast = Polymer.dom(spApp.root).querySelector('sp-toast');
spToast.display = function() {};
sinon.spy(spToast, 'display');
// Trigger the side effect that would lead to `display` being called
assert.equal(
spToast.display.calledOnces,
true
);
});

TVML listItemLockup click event

I'm using the 'Compilation.xml' template from the TVMLCatalog
I'd like to add a button click event to a 'listItemLockup'
<listItemLockup>
<ordinal minLength="2" class="ordinalLayout">0</ordinal>
<title>Intro</title>
<subtitle>00</subtitle>
<decorationLabel>(3:42)</decorationLabel>
</listItemLockup>
I've tried adding:
App.onLaunch = function(options) {
var templateURL = 'http://localhost:8000/hello.tvml';
var doc = getDocument(templateURL);
//doc.addEventListener("select", function() { alert("CLICK!") }, false);
var listItemLockupElement = doc.getElementsByTagName("listItemLockup");
listItemLockupElement.addEventListener("select", function() { alert("CLICK!") }, false);
}
addEventListener
void addEventListener (in String type, in Object listener, in optional Object extraInfo)
Is "select" the correct type?
I've been using the following tutorials
http://jamesonquave.com/blog/developing-tvos-apps-for-apple-tv-with-swift/
http://jamesonquave.com/blog/developing-tvos-apps-for-apple-tv-part-2/
Update
I'm getting an error
ITML <Error>: doc.getElementsByTagName is not a function. (In 'doc.getElementsByTagName("listItemLockup")', 'doc.getElementsByTagName' is undefined) - http://localhost:8000/main.js - line:27:58
I tried adding this to the 'onLaunch'
var listItemLockupElements = doc.getElementsByTagName("listItemLockup");
for (var i = 0; i < listItemLockupElements.length; i++) {
//var ele = listItemLockupElements[i].firstChild.nodeValue;
listItemLockupElements[i].addEventListener("select", function() { alert("CLICK!") }, false);
}
I'll see about the error first
Cross Post: https://forums.developer.apple.com/thread/17859
More common example I have seen by Apple is to define a single overall listener like:
doc.addEventListener("select", Presenter.load.bind(Presenter));
In your xml, assign unique ids to elements, or give them ways to identify them.
For example, the beginning would be something like:
load: function(event) {
var self = this,
ele = event.target,
attr_id = ele.getAttribute("id"),
audioURL = ele.getAttribute("audioURL"),
videoURL = ele.getAttribute("videoURL")
And then you can do whatever you want with your item.
if(audioURL && (event.type === "select" || event.type === "play")) {
//
}
My advice would be to study the Presenter.js file more carefully for this pattern.
Edit:
Answering your "Update" related to doc.getElementsByTagName is not a function. "doc" does not actually exist, but the general pattern is to get it with
var doc = getActiveDocument();
I assumed you would know the above.
Does that fix it?
var listItemLockupElement = doc.getElementsByTagName("listItemLockup”);
In this case, the listItemLockupElement is a NodeList, not an element. You can either iterate through the list and add an event listener to each listItemLockup, or you could add the event listener to the containing element.
When addressing items in a NodeList, you use the item(i) method rather than the standard array access notation:
listItemLockupElements.item(i).addEventListener("select", function() { })
See: https://developer.mozilla.org/en-US/docs/Web/API/NodeList/item
Adding event listeners is straightforward if you're using atvjs framework.
ATV.Page.create({
name: 'mypage',
template: your_template_function,
data: your_data,
events: {
select: 'onSelect',
},
// method invoked in the scope of the current object and
// 'this' will be bound to the object at runtime
// so you can easily access methods and properties and even modify them at runtime
onSelect: function(e) {
let element = e.target;
let elementType = element.nodeName.toLowerCase();
if (elementType === 'listitemlockup') {
this.doSomething();
}
},
doSomething: function() {
// some awesome action
}
});
ATV.Navigation.navigate('mypage');
Disclaimer: I am the creator and maintainer of atvjs and as of writing this answer, it is the only JavaScript framework available for Apple TV development using TVML and TVJS. Hence I could provide references only from this framework. The answer should not be mistaken as a biased opinion.

SAPUI5 get single property from JSON-Model

I am currently trying to figure out how I can retrieve a single value from a sap.ui.model.json.JSONModel
in my main view:
var gConfigModel = new sap.ui.model.json.JSONModel();
var getConfigCallback = function(config) {
gConfigModel.setData(config);
};
oController.getConfiguration(getConfigCallback);
console.log(gConfigModel);
in my controller:
getConfiguration : function(callback) {
var sServiceUrl = "/sap/opu/odata/sap/xxx/ConfigurationSet('Initialize')";
var config = {};
callback(config);
$.getJSON(sServiceUrl).done(function(data) {
config = data.d;
callback(config);
});
},
In my console.log statement I can see that the data was successfully passed from the backend and successfully set to the JSON model. My requirement is to store the value of attribute Editable in a single variable.
I already tried gConfigModel.getProperty('/'), didnt work. tried to access gConfigModel.oData was undefined .. How can I store it in a single value?
Solution Comment: If you catch data from a backend, you have to take care how long it takes. data can be available later then expected, in my case I added 1s timeout, afterwards I can access the property easily
setTimeout(function() {
console.log(gConfigModel.getProperty('/Editable'));
}, 1000);
I wouldn't advise using the model's getData() method since it is deprecated.
A much better solution is to use gConfigModel.getProperty("/Editable")
(I'm using the root slash here since your property resides in the root of your model)
In the same way, you can also set your data:
gConfigModel.setProperty("/Editable", <your new value>) instead
First of all, thanks for the effort to find solutions of our Problems! (at least, those regarding It stuff.. :) )
I've found a solution which I think is a little bit more save because the timeout is maybe somewhat arbitrary - it would depend on the machine or the amount of data that is to be fetched?
Therefore, I am using an attachRequestCompleted function:
with sUrl_2="path-to-my-service";
var oModel_2 = new sap.ui.model.json.JSONModel(sUrl_2);
oModel_2.attachRequestCompleted(function(data) {
//now, i can access the data stored in the oModel_2, either by getProperty, or by DOM: oModel_2.oData.d.Vendor
gv_selLieferant = oModel_2.getProperty("/d/Vendor");
gv_selEinkOrg = oModel_2.getProperty("/d/PurchOrg");
gv_selEinKGru = oModel_2.getProperty("/d/PurGroup");
});
<script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-theme="sap_bluecrystal" data-sap-ui-libs="sap.m"></script>
<script>
function getConfiguration(callback) {
var sServiceUrl = "/sap/opu/odata/sap/xxx/ConfigurationSet('Initialize')";
var config = {};
var data = {
"d": {
"_metadata": "",
"Backup01": "01",
"Editable": "True"
}
};
setTimeout((function() {
config = data;
callback(config);
})(), 2000);
};
var gConfigModel = new sap.ui.model.json.JSONModel();
var getConfigCallback = function(config) {
gConfigModel.setData(config);
alert(gConfigModel.getProperty("/d/Editable"));
};
getConfiguration(getConfigCallback);
</script>

Load JSON file to Backbone collection

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.