Setting title for multiple instances of a parameterised route page - aurelia

I define a route config as:
{ route: 'page/:id', name: 'page', moduleId: 'page', title: "Page #" }
I've also got another component listening to the router:navigation:complete event (EventAggregator), and, when a different fragment is spotted, it adds it to an array and displays this on the screen (as a sort of History list) using NavigationInstruction.config.navModel.title
When I navigate to the 'page' component with different ids time, e.g. #/page/1, #/page/2, #/page/3. I call NavigationInstruction.config.navModel.setTitle("Page " + id) from the activate() method.
In my history, I initially will see:
"Page 1"`
... then when navigating to #/page/2...
"Page 2"
"Page 2"
... then when navigating to #/page/3...
"Page 3"
"Page 3"
"Page 3"
Because the RouteConfig is shared between the different NavigationInstructions, changing the navModel.title value affects ALL NavigationInstructions derived from that RouteConfig.
Anyone got any ideas how I can set a custom title for each instance of the Page component? Is Aurelia expected to deal ok with multiple simultaneous instances of the same component?
I've considered using the new router.transformTitle hook, but as I'm likely to eventually include more information in the title, e.g. "Page 1: Contents", "Page 2: The First Chapter", that feels sub-optimal and likely to leave me doing a lot of rolling-my-own architecture to dynamically resolve the string.

I created a very simple app to test this. I did use a slightly different strategy though. I used the activate callback on the page viewmodel instead of subscribing to the router:navigation:complete event.
Here's my code:
export class Page {
activate(params, route, instruction) {
this.pageNumber = parseInt( params.id || '1' );
instruction.config.navModel.setTitle("Page " + this.pageNumber)
}
}
I'm not seeing the behavior you are seeing:
What version of the framework module are you working with?

From looking at the code, and responses (thanks #Ashley Grant), it appears that my expectations of NavigationInstruction were not accurate.
A NavigationInstruction represents a single workflow of triggering, navigation, deactivating previous pages, and activating new pages, and firing any events triggered as part of that process.
It does not - as I'd thought - represent a 'instance' of a RouteConfig (i.e. the fragment, plus params). Therefore, referring to a NavigationInstruction after the navigation:router:complete event has fired is not intended, therefore doesn't work!
I'll now rewrite my code to take a copy of the title when the navigation:router:complete event fires (this is actually non-trivial, requires calling the _buildTitle() private method on the instruction) - and have a raised a FR - https://github.com/aurelia/router/issues/469 - to request that this operation be made less opaque.

Related

Global variable is undefined if assign variable in the TargetConnected method in stimulus.js

This is the location controller file that is going to access by the html code.
export default class extends Controller {
static targets = [ "visible", "map" ]
mapTargetConnected(element) {
this.name = "aaa"
}
add(event) {
console.log(this.name) // this line is logged that variable is undefined.
}
}
here is the HTML code
<%= form_with(model: #location, local: false, url: location_path(), data: {controller: 'location', action: 'ajax:beforeSend->location#add'}) do |form| %>
....
<% end %>
This is the code regarding form submit via ajax request. if i access the this.name variable inside the add method or click event its says the variable is undefined… but if i same name variable assign it in connect() method than it’s working…
but i want to assign variable at targetConnected method and use it in the add action method.Please suggest any solution or let me know if i'm doing wrong.
Most likely the add event is being triggered before the mapTargetConnected has run.
Stimulus will go through the DOM and match elements and their targets and then trigger the relevant someTargetConnected and connect lifecycle methods once the controller is set up.
However, this is not instant and there may be some nuance to how the timing works when you are working with other events.
You will need to work out when the actual map target is being added to the DOM and possibly do some logging to check that timing compared to when the ajax:beforeSend event triggers.
Sometimes, adding a setTimeout can assist as it will ensure that the code provided to it runs 'last' (there is some nuance to this, technically it is the next event cycle).
For example
add(event) {
// here the mapTargetConnected may not have run
setTimeout(() => {
// by this point, mapTargetConnected has hopefully now run
console.log(this.name);
});
}
It is hard to offer more help without a bit more specifics on what ajax:beforeSend is and when it triggers, along with what actually adds the map target to the DOM. It may be more helpful to write this question with the initially rendered HTML output (with the minimum parts to help guide the question).
In general, it is good to remember that in the browser, things do not happen instantly, while they may be fast there can be timing issues to be aware of.

Enquire.js: Don't get the purpose of "setup" handler

I don't quite get the idea behind enquire.js' "setup" handler.
Case:
I want to load content through ajax once when you're not in a small viewport (lt 600px).
Naturally I would do enquire.register('(min-width: 600px)', { setup: myFunction });.
Problem:
Now I tested this multiple times but the setup handler also gets fired when you're in a small screen, which totally eliminates the benefit of the setup handler imo, because you would want to only load the ajax content once you enter a viewport bigger than 600px, wouldn't you?
See example jsfiddle.
Conclusion:
So actually I wouldn't even need the setup handler because I simply could load the content outside the enquire register and would have the same effect. (Which of course isn't what I want...)
Can someone tell me if I just misunderstood the purpose of setup or is there something I'm missing?
Combine with the deferSetup flag to defer the setup callback until the first match. This example illustrates the feature:
enquire.register(someMediaQuery, {
setup : function() {
console.log("setup");
},
deferSetup : true,
match : function() {
console.log("match");
},
unmatch : function() {
console.log("unmatch");
}
});
You can see a working example here: http://wicky.nillia.ms/enquire.js/examples/defer-setup/

client web - how to get current record id at any time

I'm trying to work on the "different permissions based on workflow state" issue but I'm struggling with the fact that it seems impossible to get the id of the current object 'at any time' that is necessary in order to get the permission of that object. What I mean is that I manage to get it from the client state following jquery bbq docs like:
$.bbq.getState().id
BUT it looks like this is doable only AFTER a complete page load. I investigated this by placing some alert in the main view events, like:
openerp.web.PageView = openerp.web.PageView.extend({
on_loaded: function(data) {
this._super(data);
alert('page load ' + $.bbq.getState().id);
},
do_show: function() {
this._super();
alert('page show ' + $.bbq.getState().id);
},
reload: function() {
this._super();
alert('page reload ' + $.bbq.getState().id);
},
on_record_loaded: function(record) {
this._super(record);
alert('record loaded ' + $.bbq.getState().id);
}
});
and I found that when you open the page view (by clicking on an item in a search view, for instance) you get always "undefined".
Then, you get it into "reload" and "on_record_loaded" when passing from an object to another using paged navigation. And then, you miss it again when you click on the "edit" button.
In the form view I successfully got it only on the 1st load because it seems that some caching is in-place. So that, if I place a pdb into web client's fields_view_get and I do this into the form "init_view":
var ids = [];
if ($.bbq.getState().id){
ids = [parseInt($.bbq.getState().id)];
}
console.log(ids);
return this.rpc("/web/view/load", {
"model": this.model,
"view_id": this.view_id,
"view_type": "form",
toolbar: this.options.sidebar,
context: context,
ids: ids,
}, this.on_loaded);
I get it only the 1st time that the page gets loaded. The same happen if I take ids from
this.dataset.ids
I looked anywhere at the core web module and I can't find a proper API for this and it looks weird (above all on dataset) that we don't have a proper way for getting/working on the current record/s. Even the context and the session do not have any information about that.
Probably I should store this into the view itself on 1st load...
Thanks in advance for any pointers.
try:
this.view.datarecord.id
OpenERP 7 in form view:
debugged using google chrome
Try the combination of the
this.dataset.ids and this.dataset.index
like
curr_id = this.dataset.ids[this.dataset.index]
this might solve your problem.

How do you recover the dijit registry after destroying it recursively?

I am working on an application and was doing something like this:
dojo.ready(
function(){ require['dojo/parser','dijit/registry','dojo/on'],function(.....){
//find a dijit and wrap it in event handling code.});
I was getting an error indicating that dojo was trying to register a widget with an id that was already in use. To solve the problem I entered this line of code:
//before finding the dijit destroy the existing registry.
However, logically this prevents the next line from working because now no widget exists to which I can connect an event. How can I recover the dijit ids?
The best solution is to find out why your code is trying to register a widget with an id that is already in use and change it to not to do so.
The #mschr's solution should work, but I would advise again using it, as it can break your code in many other places and you are likely to spend hours investigating strange behavior of your application.
Anyway, if you are willing to do it that way and automatically destroy widgets with the same ID, do not override registry.add() method. You could do it, but it does not mean, you should do it (especially in programming). Employ dojo/aspect instead to call a function that will destroy the widget with the same ID before registry.add() is called:
require([
"dojo/aspect",
"dijit/registry"
], function(
aspect,
registry
) {
aspect.before(registry, "add", function(widget) {
if(registry.byId(widget.id)) {
registry.byId(widget.id).destroy();
// this warning can save you hours of debugging:
console.warn("Widget with id==" + widget.id + " was destroyed to register a widget with the same id.");
}
return [widget];
});
});
I was myself curious how to accomplish #mschr solution without that override, so I created an jsFiddle to experiment: http://jsfiddle.net/phusick/feXVT/
What happens once you register a dijit is the following; it is referenced by the dijit.registry._hash:
function (widget) {
if (hash[widget.id]) {
throw new Error("Tried to register widget with id==" + widget.id + " but that id is already registered");
}
hash[widget.id] = widget;
this.length++;
}
Now, every now and then you would have a contentpane in which you would put a widget programatically (programatically, hence dojo.parser handles cpane.unload and derefences / destroys parser-instantiated widgets).
When this happens, you need to hook onto some form of 'unload', like, when your call cpane.set('content' foo) or cpane.set('href', bar). Hook is needed to destroy and unregister the instances you keep of widgets - otherwise you would have a memoryleak in your program.
Normally, once an object has no references anywhere - it will get cleaned out of memory however with complex objects such as a widget might be, 'class-variables' often have reference to something _outside _widget scope which flags the widget unsafe to delete to the garbage collector... Once you get this point, you will know to perform proper lifecycles, yet not before the concept is fully understood..
What you could do is to override the dijit.registry with your own handler and have any widgets that are doublets destroyed automatically like so:
// pull in registry in-sync and with global scoped
// accees (aka dijit.registry instead of dj_reg)
require({
async:false,
publishRequireResult:true
}, [
"dijit.registry"
], function(dj_reg) {
dijit.registry.add = function(widget) {
// lets change this bit
if (this._hash[widget.id]) {
this._hash[widget.id].destroy(); // optinally destroyRecursively
this.remove(widget.id)
}
this._hash[widget.id] = widget;
this.length++;
}
});

Cant handle it (jQuery hanlder understanding needed)

I'm embarrassed to even ask BUT could someone help me understand what a "handler" is. I am new to jQuery and the API constantly has references similar to the following:
toggle( handler(eventObject), handler(eventObject), [ handler(eventObject) ] )
I scratch my head and say to myself "what the hell is a handler". Then I check my 2 jquery books and don't really see anything specific there. I get what an event handler does, it handles an event. But the word handler in the above context confuses me including "eventObject". I tried to google it but could not really find a really clear definition of what exactly a handler is as it relates to jquery. Thanks for your help =]
Handlers are any functions that you write to handle events. For e.g. in
$(document).ready(function() {
//......
});
the handler is
function() {
//.......
}
Think of a handler as a callback for whatever operation is being invoked. In the case of handler(eventObject) it means that the method with that parameter can accept a function being passed to it and that function will be called at some specific point in time before, during, or after the execution of the method receiving it (as indicated by the parameter specification) and it will be passed a value called eventObject which can be anything, but is most likely the target of the given event your callback is being issued for.
Here's an example:
function MyCallback(eventObject) {
alert(jQuery(eventObject).attr('id') + ' toggled'));
}
jQuery("#myBtn").click(function() {
jQuery("#myObj").toggle("fast", function(eventObject) { MyCallback(eventObject); });
});
With the above code, when #myBtn is clicked the element #myObj will be toggled (fast) and as soon as the toggle animation completes MyCallback will be called and passed #myObj which will cause an alert to appear saying, "myObj toggled".
This is the function which will handle the event. To expand, in the case of toggle, ON calls the first function (with the eventObject) and OFF calls the second function. eventObject will hold different info depending on events, like coordinates of the mouse.