Templatizer - How to render multiple times same template, Polymer 2.x - polymer

In Polymer 1.x I was used to write a templatize code like this:
renderTemplate(query, properties) {
let element = this.shadowRoot.querySelector(query);
this.templatize(element);
var instance = this.stamp(properties);
return instance;
}
which worked well. But in Polymer 2.x there is a new error message A <template> can only be templatized once. Well it doesn't make sense, because I have 1 template which I want to redistribute multiple times with different properties.
I am giving here an example of how is my code
I have #template1 and #template2
I want to render #template1 then #template2 then #template1.
In steps how I render templates:
1) templatize #template1
2) stamp properties
3) templatize #template2
4) stamp properties
5 a) templatize #template1 => ERROR
5 b) skip templatize and stamp properties => #template2 is rendered....
How am i able to make this possible? calling stamp() after rendering #template2 will result in another #template2 render. I want #template1, but I can't templatize #template1 because it has been already templatized. And stamp is always "binded" to last templatized element.
Am I doing something wrong? I do really hate Polymer because of it's bad documentation and hard to google something usefull

I found a workaround which is propably not the best solution but it works. I tried to search in source code for some solutions but there wasn't anything usefull except the one property called __templatizeOwner. This property is set to all templatized elements. Removing this property from an element is the way.
renderTemplate(query, properties) {
let element = this.shadowRoot.querySelector(query);
if(element.__templatizeOwner) {
element.__templatizeOwner = null;
}
this.templatize(element);
var instance = this.stamp(properties);
return instance;
}
I am not sure what side effects this might have (more memory usage or something) but this is the only way I was able to find out.

Related

How to access the style attribute of Primeng table

In an angular project, I need to test that the displayed table width of the primeng data table is set to the maxWidth value i assign to it. To do so, i want to call the [style] attribute to get the width and see if its equal to my maxWidth. However, i do not know how to call attributes like this. How do i go about this? Currently i have no clue if I'm going in the correct direction.
I have tried several things but I am not sure of the syntax for it.
<p-table class="p-table" ... [style] = "{width: maxWidth}" >
it('should implement maxwidth', () => {
const widthDebug: DebugElement = fixture.debugElement;
const tableWidth = widthDebug.query(By.css('.ui-table .ui-widget'));
const ptable: HTMLElement = tableWidth.nativeElement;
expect(ptable.textContent).toContain("width: " + component.maxWidth);
});
expected: success (ptable.textContent contains "width: component.maxWidth")
actual: TypeError: cannot read property 'nativeElement' of null
I see that it's now two months after you asked your question, so it's probably too late for my answer to help, but I stumbled across this post while looking up something else about PrimeNG, so I might as well give it a shot.
The problem here is that nativeElement is defined on Dialog class instances of the Angular p-table component. It's not defined on any particular DOM element.
By.css('.ui-table .ui-widget') is going to find a DOM element for you, not an Angular class instance. In particular what will be found is a <div> inside the <p-dialog> DOM element, and it's this <div> that receives the style set via [style]=....
As your code is written above tableWidth.style.width would contain (as a string) the value of maxWidth that you're expecting to find.

Polymer: register a behaviour at runtime

I need to setup the behaviour of a polymer web-compontent at runtime. I tried to change the "behaviours" array by pushing the new behaviour, but it didn't work. Is there a proper way to do it?
I'm trying to create a table web-component with a pager at bottom. It should be extensible allowing the loading of data from a javascript array, a restful service or a custom source. Thus, I decided to create a behaviour for each one of these source and change it when the source changes. Is it a correct way to design it?
Here as example the source code of the behaviour to load data from an array. It has the following function:
itemsLoad: function(page, itemsPerPage, callback) {...
which is called from the web-component to load data of a specific page. My idea is that each behaviour based on the type of data source (e.g. CSV, JSON, etc.) will implement this method in a different way. Then, the behaviour will be registered at run-time, because is at run-time that the developers knows which is the source to use.
I don't think you will be able to change behaviours at run-time, because they are mixed into the element prototype.
What you can do is create a separate element for each of your cases (csv, json, etc) and create nodes dynamically as required. You could than place that element inside your grid
<table-component>
<json-data-source></json-data-source>
</table-component>
The <table-component> would look for a child element which implements itemsLoad to get the data.
EDIT
To work with child nodes you would use Polymer's DOM API. For example you could listen to added child nodes and select one that implements the itemsLoad method.
Polymer({
attached: function() {
Polymer.dom(this).observeNodes(function(info) {
var newNodes = info.addedNodes;
for(var i=0; i<newNodes.length; i++) {
var dataSource = newNodes[i];
if(dataSource.itemsLoad && typeof dataSource.itemsLoad === 'function') {
this.loadItems(dataSource);
break;
}
}
});
}
loadItems: function(dataSource) {
dataSource.itemsLoad().then(...);
}
});
You could replace Polymer.dom(this).observeNodes with simply iteration over Polymer.dom(this).children. Whichever works best for you.

How to use Archetype with Razor?

I can't believe I couldn't find examples online.
This is my simple Archetype.
This is what I tried:
<img src="#CurrentPage.ctaTopLeft.image" alt="#CurrentPage.ctaTopLeft.text">
but it gives this error:
'Archetype.Models.ArchetypeModel' does not contain a definition for 'image'
EDIT: This works:
<img src="#CurrentPage.GetPropertyValue("ctaTopLeft").Fieldsets[0].GetValue("image")" alt="#CurrentPage.GetPropertyValue("ctaTopLeft").Fieldsets[0].GetValue("text")">
Wondering if there is any shorter way of writing it?
Well, no - an Archetype property can have a complex, nested set of data quite often in collections which may also be nested. In fact, it's quite common to use a corresponding nested set of partial views just to render it out correctly if you have for example nested Archetype properties (it happens).
There are some tutorials/samples available for this sort of thing:
http://imulus.github.io/Archetype/ - Archetype home on Github
https://gist.github.com/kgiszewski/8863822 - this one is linked from the Archetype page above - gives some examples of usage with Razor/MVC.
There are also other packages designed to help you map Archetype properties to POCO as well - e.g. https://our.umbraco.org/projects/developer-tools/archetype-mapper/
I prefer the typed way of getting the properties.
var property = Model.Contet.GetPropertyValue<ArchetypeModel>("yourArchetypePropertyAlias");
if (property != null && property.Any()) {
foreach (var item in property) {
var imageId = item.GetValue<int>("yourImagePropertyAlias");
var text = item.GetValue<string>("yourTextPropertyAlias");
}
}

Android ListView binding programmatically

There are many examples of doing this in axml, but I would like to have a complete binding using code behind. To be honest, I would like to have NO axml, but seems like creating all the controls programmatically is a nightmare.
I first tried the suggestions at:
MvxListView create binding for template layout from code
I have my list binding from code-behind, and I get six rows (so source binding is working); but the cells itself does not bind.
Then at the following url:
Odd issue with MvvmCross, MvxListViewItem on Android
Stuart has the following comment: Have looked through. In this case, I don't think you want to use DelayBind. DelayBind is used to delay the binding action until next time the DataContext is set. In Android's MvxAdapter/MvxListItemView case, the DataContext is passed in the ctor - so DataContext isn't set again until the cell is reused. (This is different to iOS MvxTableDataSource).
So in essence, the only example I see shows DelayBind, which shouldn't work.
Can someone please show me some examples... thanks in advance.
Added reply to Comments:
Cheesebaron, first of all, a huge thank you and respect for all your contributions;
Now, why not use axml? Well, as programmers, we all have our own preferences and way of doing stuff - I guess I am old school where we didn't have any gui designer (not really true).
Real reasons:
Common Style: I have a setup where Core has all the style details, including what all the colors would be. My idea is, each platform would get the style details from core and update accordingly. It's easy for me to create controls with the correct style this way.
Copy-Paste across platform (which then I can even have as linked files if I wanted). For example, I have a login screen with web-like verification, where a red error text appears under a control; overall on that screen I have around 10 items that needs binding. I have already got iOS version working - so starting on Droid, I copied the whole binding section from ios, and it worked perfectly. So, the whole binding, I can make it same across all platform... Any possible error in my way will stop at building, which I think is a major advantage over axml binding. Even the control creation is extremely similar, where I have helpers with same method name.
Ofcourse I understand all the additional layout that has to be handled; to be honest, it's not that bad if one really think it through; I have created a StackPanel for Droid which is based on WP - that internally handles all the layouts for child views; so for LinearLayout, all I do is setup some custom parameters, and let my panel deal with it. Relative is a different story; so far, I have only one screen that's relative, and I can even make it Linear to reduce my additional layout code.
So, from my humble point of view, for my style, code-behind creation allows me to completely copy all my bindings (I do have some custom binding factories to allow that), copy all my control create lines; then only adding those controls to the view is the only part that is different (then again, droid and WP are almost identical). So there is no way I can miss something on one platform and all are forced to be the same. It also allows me to change all the styles for every platform just by changing the core. Finally, any binding error is detected during compile - and I love that.
My original question wasn't about NOT using axml... it was on how to use MvxListView where all the binding is done in code-behind; as I have explained, I got the list binding, but not the item/cell binding working.
Thanks again in advance.
Here is part of my LoginScreen from droid; I think it's acceptable amount of code for being without axml file.
//======================================================================================================
// create and add all controls
//======================================================================================================
var usernameEntry = ControlHelper.GetUITextFieldCustom(this, "Username.", maxLength: 20);
var usernameError = AddErrorLabel<UserAuthorization, string>(vm => ViewModel.Authorization.Username);
var passwordEntry = ControlHelper.GetUITextFieldCustom(this, "Password.", maxLength: 40, secureTextEntry: true);
var passwordError = AddErrorLabel<UserAuthorization, string>(vm => ViewModel.Authorization.Password);
var loginButton = ControlHelper.GetUIButtonMain(this);
var rememberMe = new UISwitch(this);
var joinLink = ControlHelper.GetUIButtonHyperLink(this, textAlignment: UITextAlignment.Center);
var copyRightText = ControlHelper.GetUILabel(this, textAlignment: UITextAlignment.Center);
var copyRightSite = ControlHelper.GetUIButtonHyperLink(this, textAlignment: UITextAlignment.Center);
var layout = new StackPanel(this, Orientation.Vertical)
{
Spacing = 15,
SubViews = new View[]
{
ControlHelper.GetUIImageView(this, Resource.Drawable.logo),
usernameEntry,
usernameError,
passwordEntry,
passwordError,
loginButton,
rememberMe,
joinLink,
ControlHelper.GetSpacer(this, ViewGroup.LayoutParams.MatchParent, weight: 2),
copyRightText,
copyRightSite
}
};
I just came across a similar situation myself using Mvx4.
The first link you mentioned had it almost correct AND when you combine it from Staurts comment in the second link and just remove the surrounding DelayBind call, everything should work out ok -
public class CustomListItemView
: MvxListItemView
{
public MvxListItemView(Context context,
IMvxLayoutInflater layoutInflater,
object dataContext,
int templateId)
: base(context, layoutInflater, dataContext, templateId)
{
var control = this.FindViewById<TextView>(Resource.Id.list_complex_title);
var set = this.CreateBindingSet<CustomListViewItem, YourThing>();
set.Bind(control).To(vm => vm.Title);
set.Apply();
}
}
p.s. I have asked for an Edit to the original link to help others.

AS3 Object indexing causing Flixel misbehaviour--what's wrong with this code?

I'm getting my feet wet with AS3, Flixel and component/entity systems (yes, all at the same time), and my entities (which subclass FlxSprite) aren't being added correctly (i.e., not at all). I've just spent a good two hours nailing down the offending line. If I remove it, the rest of the game chugs along happily.
What's wrong with this code?
public function addComponent(c:Component):void
{
var type:String = Object(c).constructor.toString();
FlxG.log("type=" + type);
this._components[type] = c; // The evil line
FlxG.log("now type=" + _components[type]);
c.setData(this);
}
components is an Object field being used as a map/dictionary. type gets set to [class PlayerComponent]. Based on googling, this is valid and should work as intended.
Based on the output from the console, it's just bailing after that line--not crashing entirely. What's going on? More details gladly offered upon request.
I'm not certain about Component - not my forte - but I do know that FlxGroup and its children (which include FlxState) have a method called add() which adds children to them.
So if you have an FlxSprite, the correct way (in flixel) to add it to the chain of things to update/draw is to use that; you can add it directly to your state or to a group that is a child of the state.
Function docs: http://flixel.org/docs/org/flixel/FlxGroup.html#add()