Aurelia Routing: Append Views into Tabbed Interface - aurelia

I'm practically brand new to Aurelia, but over the course of a few days I've picked up the starter template and gone through some video training in Pluralsight. I have a unique vision that I can't seem to decide whether compose element, custom element, or router is best to use for this scenario - or if I need to write something completely custom.
I prefer to continue using the router because it gives you the
URLs and history state. Linking deep within the web app may be necessary.
When a view / viewmodel is initialized, I want the view appended to the DOM, NOT replaced. The <router-view> element works by replacing the view.
With each view appended to the DOM, I would like to create a set of tabs representing every view that has been opened so far. Think of any modern text editor, IDE, or even a web browser shows tabs.
Sometimes it would be necessary to detect whether a view is already rendered in the DOM (viewmodel + parameter) and just bring that view to the front -vs- appending the new one.
Do you have any suggestions, examples, etc for someone relatively new to Aurelia, SPAs, and MVVM?
Thank you.

I believe the easiest way is using the compose element. You would need an array containing all screens, and another array to hold the opened screens. Something like this:
screens = [
{ id: 1, name: 'Test 1', view: './test-1.html', viewModel: './test-1' },
{ id: 2, name: 'Test 2', view: './test-2.html', viewModel: './test-2' }
];
_activeScreens = [];
get activeScreens() {
return this.screens.filter((s) => this._activeScreens.indexOf(s.id) !== -1);
}
In the HTML you just have to use <compose></compose> for each iteration of activeScreens.
I made this example https://gist.run/?id=c32f322b1f56e6f0a83679512247af7b to show you the idea. In my case, I've used an html table. In your case, you could use a tab plugin, like Bootstrap or jQuery.
Hope this helps!

Related

Aurelia - dynamically create custom element in a view-model

I have an Aurelia app where a user can click on a button and create a new tab. The tab and its content (a custom element) do not exist on the page before the user clicks the button. I am generating the HTML for the content at runtime (via Javascript) in my view model.
I keep seeing mention of using the template engine's compose or enhance functions, but neither are working for me. I don't know how I would use the <compose> element (in my HTML) since I am creating the element based on the user clicking a button.
My thought was that the button has a click.delegate to a function that does ultimately does something like
const customElement = document.createElement('custom-element');
parentElement.appendChild(customElement);
const view = this.templatingEngine.enhance({
element : customElement,
container : this.container, // injected
resources : this.viewResources, // injected
bindingContext: {
attrOne: this.foo,
attrTwo: this.bar,
}
});
view.attached();
But all this does is create an HTML element <custom-element></custom-element> without actually binding any attributes to it.
How can I create a custom element analogous to <custom-element attr-one.bind="foo" attr-two.bind="bar"></custom-element> but via Javascript?
As you pointed out in your own answer, it's the missing resources that caused the issue. One solution is to register it globally. That is not always the desired behavior though, as sometimes you want to lazily load the resources and enhance some lazy piece of HTML. Enhance API accepts an option for the resources that you want to compile the view with. So you can do this:
.enhance({
resources: new ViewResources(myGlobalResources) // alter the view resources here
})
for the view resources, if you want to get it from a particular custom element, you can hook into the created lifecycle and get it, or you can inject the container and retrieve it via container.get(ViewResources)
I found the problem =\ I had to make my custom element a global resource.

Initialize dynamic Component in Code using Vue.js

I am currently developing a web application that is used to display elements for events on a map provided by HERE Maps. I am using Vue.
I have some components, but the relevant component is the component HereMaps.vue which initializes the map using the HERE Maps Api.
The HERE Maps Api provides the possibility to place so called InfoBubbles on the map showing additional information. These InfoBubbles can be provided some HTML-code in order to customize their appearance.
Please refer to the documentation for additional information
Following the documentation the code looks something like this:
let bubble = new H.ui.InfoBubble(marker.getPosition(), {
content: "<div class='someClass'>Some Content</div>"
});
this.ui.addBubble(bubble)
This is happening after mount in the "mounted" method from Vue in the "HereMaps" component.
The Bubbles are added in a "closed" (hidden) form and dynamically "opened" to reveal their content when the corresponding marker icon on the map is clicked. Therefore the HTML-code is present on the DOM after the component is mounted and is not removed at a later stage.
Now instead of supplying custom code within each bubble added to the UI i want to just add a component like this:
let bubble = new H.ui.InfoBubble(marker.getPosition(), {
content: "<myDynamicComponent></myDynamicComponent>"
});
this.ui.addBubble(bubble)
It does not matter to me wether the component is initialized using props or if it is conditionally rendered depending on the state of a global variable. I just want to be able to use the "myDynamicComponent" in order to customize the appearance in a different file. Otherwise the design process gets very messy.
As far as i know this is not possible or at least i was not able to get it work. This is probably due to the fact that the "myDynamicComponent" is not used within the "template" of the "HereMaps" component und thus Vue does not know that it needs to render something here after the directive is added to the DOM in the "mounted" method.
This is what the InfoBubble looks using normal HTML as an argument:
This is what the InfoBubble looks using the component as an argument:
It appears to just be empty. No content of the "myDynamicComponent" is shown.
Does anyone have any idea how i could solve this problem.
Thank You.
Answer is a bit complicated and I bet you wouldn't like it:)
content param can accept String or Node value. So you can make new Vue with rendered your component and pass root element as content param.
BTW, Vue does not work as you think, <myDynamicComponent></myDynamicComponent> bindings, etc exists in HTML only in compile time. After that all custom elements(components) are compiled to render functions. So you can't use your components in that way.
Give us fiddle with your problem, so we can provide working example:)

Can Vue-Router handle clicks from normal anchors rather than router-link?

I have a scenario where there are two major components on a page; a frame-like component that contains common functionality for many applications (including a bookmark/tab bar) and my actual application code.
Since the frame doesn't actually own the page that it's included on, it seems like it would be incorrect for it to define any routes, however the current page may define their own routes that may match one of those links. In that case, I'd like vue-router to handle those anchor clicks and navigate appropriately rather than doing a full page reload.
Here's a simplified template of what this looks like:
Frame (an external dependency for my app):
<Frame>
<TabStrip>
</TabStrip>
<slot></slot>
<Frame>
App1:
<Frame>
<App>You're looking at: {{ pageId }}!</App>
</Frame>
So when any of the app1 domain links are clicked from that tab strip, I want my route definitions in app1 to pick that up rather than it causing a page load. Since that component is owned by the frame, I don't have access to write <router-link> since links to many different apps may co-exist there.
Any thoughts?
Whoo, this is an old one! However, since this question was high in my search results when I was researching this problem, I figured I should answer it.
My use-case was similar to the one in the comments: I needed to capture normal <a> links within rendered v-html and parse them through the router (the app is rendering Markdown with a light modification that generates internal links in some cases).
Things to note about my solution:
I'm using Vue3, not Vue2; the biggest difference is that this is the new Vue3 composition-style single page component syntax, but it should be easy to backport to Vue2, if necessary, because the actual things it's doing are standard Vue.
I stripped out the markdown logic, because it doesn't have anything to do with this question.
Note the code comment! You will very likely need to design your own conditional logic for how to identify links that need to be routed vs. other links (e.g. if the application in the original question has same-origin links that aren't handled by the Vue app, then copy/pasting my solution as-is won't work).
<script setup>
import { useRouter } from "vue-router"
const router = useRouter()
const props = defineProps({
source: {
type: String,
required: true,
},
})
function handleRouteLink(event) {
const target = event.target
// IMPORTANT! This is where you need to make a decision that's appropriate
// for your application. In my case, all links using the same origin are
// guaranteed to be internal, so I simply use duck-typing for the
// properties I need and compare the origins. Logic is inverted because I
// prefer to exit early rather than nest all logic in a conditional (pure
// style choice; works fine either way, and a non-inverted conditional is
// arguably easier to read).
if (!target.pathname || !target.origin || target.origin != window.location.origin) {
return
}
// We've determined this is a link that should be routed, so cancel
// the event and push it onto the router!
event.preventDefault()
event.stopPropagation()
router.push(target.pathname)
}
</script>
<template>
<div v-html="source" #click="handleRouteLink"></div>
</template>

Load AngularJS Template within page, dynamically

I have a page containing 2 controllers: one which manages a list of so-called 'apps', and another that is to place the new Angular template into the innerHTML of its Div element.
<div ng-controller="appList"></div>
<div ng-controller="appPane"> Dynamic content should be loaded here! </div>
I have tried using the standard {{expression}} bindings, but they do not work with html, I have also tried the ng-bind-html-unsafe directive (Binding the innerhtml to that of the App request's return) but controllers are not executed within this new code.
The problem seems to be that by using a Binding, Angular is not re-parsing the contents of the html in question to use it as an angular app. Any ideas of how to get it to parse dynamic content?
It appears that the $compile service, when fed the elements you wish to recompile along with your current scope, does what I was looking for.
Example from my source:
var appPane = $('#AppPane');//JQuery request for the app pane element.
appPane.html(data);//The dynamically loaded data
$compile(appPane.contents())($scope);//Tells Angular to recompile the contents of the app pane.
This should help anyone experiencing my problem, I hope.
Look at $routes and ngView in angularjs.
Here's a very basic example:
http://jsfiddle.net/pXpja/3/
Take a look at the uiRouter module (from the AngularUI project). It adds the concept of states, which are pretty similar to routes, but with other goodies, such as the ability to nest them. For example:
$stateProvider
.state('myState', {
url: '/mystate',
templateUrl: '...',
controller: 'MyCtrl'
})
.state('myState.substate', {
url: '/{substate}',
templateUrl: '...',
controller: 'MySubCtrl'
});
MySubCtrl will be activated whenever you go to /mystate/something and you can use that "something" as a parameter (see $stateParams). You can nest states to any amount of levels.

Where should a new XTemplate be defined using Sencha Touch 2?

I am building my first app with ST2 and began by building the app outlined in Getting Started with Sencha Touch 2 and then taking that and trying to modify it so it met my own needs. The demo app has a DataView List where each element can be tapped to reveal a corresponding detail page.
In that app the content on the detail pages is being pulled in dynamically and does not need to be styled or arranged much. However, for my own detail pages I need to use a Template or XTemplate to style and position my data.
I can't seem to figure out where I should define the template (ie, var myTpl = new Ext.XTemplate(...)) —In the controller, in the model?
Any guidance on this front would be much appreciated.
This depends on where you want to use the XTemplate. If it is only ever going to be used in one view, then just define the xtemplate when you defined the view.
{
xtype : 'view',
tpl : new XTemplate('<div></div>...')
}
If you are going to use it in multiple views, then you can create a class that has a sole purpose of sharing templates.
Ext.define('MyApp.util.SharedTemplates', {
statics : {
sharedTemplate1 : new XTemplate('<div></div>')
}
});
This way the template only gets compiled once and is re-useable.