Dynamic view creation - aurelia

I'm trying to get a simple dynamic view working the simplest possible way.
import {inject, noView, ViewCompiler, ViewSlot} from 'aurelia-framework';
#noView
#inject(ViewCompiler, ViewSlot)
export class ButtonVM{
constructor(vc, vs){
this.viewCompiler = vc;
this.viewSlot = vs;
var viewFactory = this.viewCompiler.compile('<button>Some button</button>');
but apparantly I'm missing something, the view factory should be able to create a view and then it should be added to a viewslot?
What am I missing in the above code?
I should mention that I tried to follow Rob's comments in this thread:
https://github.com/aurelia/templating/issues/35

See the updated post by Rob in the same thread.
import {inject, noView, ViewCompiler, ViewSlot, Container, ViewResources} from 'aurelia-framework';
#noView
#inject(ViewCompiler, ViewSlot, Container, ViewResources)
export class Test {
constructor(vc, vs, container, resources){
this.viewCompiler = vc;
this.viewSlot = vs;
var viewFactory = this.viewCompiler.compile('<button>${title}</button>', resources);
var bindingContext = { title:'Click Me'};
var view = viewFactory.create(container, bindingContext);
this.viewSlot.add(view);
this.viewSlot.attached();
}
}

Late for an answer but this can be easily achieved by using getViewStartegy method provided by aurelia.
export class Test {
constructor(vc, vs, container, resources){
}
getViewStrategy() {
return new InlineViewStrategy('<button>${title}</button>');
}
}

Related

mixpanel-react-native initialization

In one of the sample apps in the mixpanel-react-native repo Mixpanel is initialized like this from a separate Analytics.js file, what's the benefit of doing it this way or what's the reasoning behind doing it this way?
import {Mixpanel} from 'mixpanel-react-native';
import {token as MixpanelToken} from './app.json';
export class MixpanelManager {
static sharedInstance = MixpanelManager.sharedInstance || new MixpanelManager();
constructor() {
this.mixpanel = new Mixpanel(MixpanelToken);
this.mixpanel.init();
this.mixpanel.setLoggingEnabled(true);
}
}
export const MixpanelInstance = MixpanelManager.sharedInstance.mixpanel;

Spartacus Multisite Site Specific Configuration

We'd like to store some site-specific config on the frontend in Spartacus.
For example: Each site (of a multisite setup) has a different Google API Key.
Right now, I've built a CONFIG_INITIALIZER factory, like the following. But with the fake scoping and all, it does not seem the correct way to do this.
import { Inject, Injectable } from '#angular/core';
import { ConfigInitializer, ConfigInitializerService, deepMerge } from '#spartacus/core';
import { StoreFinderConfig } from '#spartacus/storefinder/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { MultiSiteConfigChunk } from './multisiteconfig-tokens';
#Injectable({ providedIn: 'root' })
export class MultisiteConfigInitializer implements ConfigInitializer {
// Fake scoping :(
readonly scopes = ['all'];
readonly configFactory = () => this.resolveConfig().toPromise();
constructor(
protected configInit: ConfigInitializerService, #Inject(MultiSiteConfigChunk) private multiSiteConfig: Array<any>) {
}
protected resolveConfig(): Observable<StoreFinderConfig> {
return this.configInit.getStable('context.baseSite').pipe(
map((config) => {
const mergedConfig = deepMerge(...this.multiSiteConfig);
return mergedConfig[config.context.baseSite];
})
);
}
}
What would be the recommended way to get be able to do this?
You can check this doc first: https://sap.github.io/spartacus-docs/automatic-context-configuration/#adding-a-custom-context
If you are using automatic context configuration, you also can try this:
extends SiteContextConfigInitializer (inject your multiSiteConfig in the child class); replace SiteContextConfigInitializer using the child in providers.
replace getConfig function in child class to add the Google API Key to site-context.

Dynamically updating Polyline points in tornadofx

This question is a bit simplistic, but i couldn't figure it out for myself... What I'm trying to do is using a JavaFX Timeline to update my Polyline points. What I've got until now is as follows:
class MainView : View("Hello TornadoFX") {
var myLine: Polyline by singleAssign()
val myTimeline = timeline {
cycleCount = INDEFINITE
}
override val root = hbox {
myLine = polyline(0.0, 0.0, 100.0, 100.0)
myTimeline.apply {
keyFrames += KeyFrame((1/10.0).seconds, {
myLine.points.forEachIndexed { i, d ->
myLine.points[i] = d + 1
}
println(myLine.points)
})
play()
}
}
}
Although the point list does update the values, as shown when printing them, the change is not reflected in the ui.
Thank you very much for your help!
I have not worked with TornadoFX earlier, so I gave a try with the normal JavaFX. Looks like the the UI is updating when the points are updated. May be the issue is something related to your implementation with TornadoFX.
Please check below the working example.
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Polyline;
import javafx.stage.Stage;
import javafx.util.Duration;
public class PolyLinePointsUpdateDemo extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
Pane root = new Pane();
Scene scene = new Scene(root, 600,600);
primaryStage.setScene(scene);
primaryStage.setTitle("PolyLine Points Update");
primaryStage.show();
Polyline line = new Polyline(0.0, 0.0, 100.0, 100.0);
root.getChildren().add(line);
Timeline timeline = new Timeline();
timeline.getKeyFrames().add(new KeyFrame(Duration.millis(250), e->{
for (int i = 0; i < line.getPoints().size(); i++) {
double d = line.getPoints().get(i);
line.getPoints().set(i, d+1);
}
System.out.println(line.getPoints());
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
public static void main(String... a){
Application.launch(a);
}
}
Figured out that the issue was simply using an hbox as the parent layout, instead of a pane, which handles the chidren positioning with absolute coordinates.

Is it possible to make a function or class available to all views in Aurelia?

The use case is as follows: We would like to have elements hidden or shown, based on the user's permissions.
The ideal way would be something like this:
<div if.bind="foo != bar && hasPermission('SOME_PERMISSION')"></div>
hasPermission() would in that case be a function that was automatically injected into all viewmodels.
Is that possible? I know we could use base classes for this, but we'd like to avoid that to stay as flexible as possible.
If you're willing to pay the price of a global function (global as in window), import it in your app-bootstrap file, like so:
has-permission.js
export function hasPermission(permission) {
return permission.id in user.permissions; // for example...
}
main.js
import 'has-permission';
export function configure(aurelia) {
// some bootstrapping code...
}
If the service you want to publish globally is a view, you can sidestep exposing it on the window and tell Aurelia's DI to make it available everywhere so you won't have to declare it in every dependent client.
To do so, pass its module ID in the FrameworkConfiguration#globalResources() configuration function:
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.globalResources('my-kick-ass-view', 'my-awesome-converter');
aurelia.start().then(a => a.setRoot());
}
If you have a service which deals with user permission, it can be injected in all your view-models.
export class UserPermissionService
{
hasPermission(user, permission)
{
return false;
}
}
#inject(UserPermissionService)
export class Users {
userPermissionService;
constructor(userPermissionService) {
this.userPermissionService = userPermissionService;
...
}
hasPermission(user, p)
{
return this.userPermissionService.hasPermission(user, p);
}
}
If you still don't like this, other options are:
a value converter http://aurelia.io/docs.html#/aurelia/binding/1.0.0-beta.1.2.1/doc/article/binding-value-converters
a custom attribute (similar to if it will hide the element)
http://www.foursails.co/blog/custom-attributes-part-1/
depending on what you need, both can use the UserPermissionService singleton from above
Add a .js file in your folder, with export function
ex: utility.js
export function hasPermission(permission) {
return true/false;
};
import the function in view-model
import {hasPermission} from 'utility';
export class MyClass{
constructor(){
this.hasPermission = hasPermission;
}
}
view.html
<div if.bind="foo != bar && hasPermission('SOME_PERMISSION')"></div>

Blank SWF file and no errors when compiling ActionScript 3.0 class through mxmlc compiler

I have two action-script classes one is instantiated in the other. It works fine in flash professional cc but when I use the mxmlc compiler via the command prompt, it compiles a blank swf without any errors.
Monster.as
package {
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.display.Sprite;
import flash.display.Loader;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundMixer;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class Monster extends Sprite {
public function Monster() {
// constructor code
var imageLoader: Loader = new Loader();
var image: URLRequest = new URLRequest("female-monster.png");
imageLoader.load(image);
addChild(imageLoader);
imageLoader.x = 0;
imageLoader.y = 0;
}
public function roar():void {
var mySound: Sound = new Sound();
mySound.load(new URLRequest("monster.mp3"));
mySound.play();
}
public function visibleMonster():void {
this.alpha = .5;
}
}
}
addMonster.as
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import Monster;
public class addMonster extends MovieClip {
public var monster:Monster;
public function addMonster() {
// constructor code
monster = new Monster();
addChild(monster);
monster.roar();
monster.moveMonster();
monster.visibleMonster();
}
}
}
Is it possible that there are options I need to use when running the command to compile?
Solved problem by closing Dreaweaver and Flash applications which were using the file I was trying to run mxmlc compiler to compile the as file.