Durandal, get path of the current module - durandal

Is there a way in Durandal to get the path of the current module? I'm building a dashboard inside of a SPA and would like to organize my widgets in the same way that durandal does with "FolderWidgetName" and the folder would contain a controller.js and view.html file. I tried using the getView() method in my controller.js file but could never get it to look in the current folder for the view.
getView(){
return "view"; // looks in the "App" folder
return "./view"; // looks in the "App/durandal" folder
return "/view"; // looks in the root of the website
return "dashboard/widgets/htmlviewer/view" //don't want to hard code the path
}
I don't want to hardcode the path inside of the controller
I don't want to override the viewlocator because the rest of the app still functions as a regular durandal spa that uses standard conventions.

You could use define(['module'], function(module) { ... in order to get a hold on the current module. getView() would than allow you to set a specific view or, like in the example below, dynamically switch between multiple views.
define(['module'], function(module) {
var roles = ['default', 'role1', 'role2'];
var role = ko.observable('default');
var modulePath = module.id.substr(0, module.id.lastIndexOf('/') +1);
var getView = ko.computed(function(){
var roleViewMap = {
'default': modulePath + 'index.html',
role1: modulePath + 'role1.html',
role2: modulePath + 'role2.html'
};
this.role = (role() || 'default');
return roleViewMap[this.role];
});
return {
showCodeUrl: true,
roles: roles,
role: role,
getView: getView,
propertyOne: 'This is a databound property from the root context.',
propertyTwo: 'This property demonstrates that binding contexts flow through composed views.',
moduleJSON: ko.toJSON(module)
};
});
Here's a live example http://dfiddle.github.io/dFiddle-1.2/#/view-composition/getView

You can simply bind your setup view to router.activeRoute.name or .url and that should do what you are looking for. If you are trying to write back to the setup viewmodels property when loading you can do that like below.
If you are using the revealing module you need to define the functions and create a module definition list and return it. Example :
define(['durandal/plugins/router', 'view models/setup'],
function(router, setup) {
var myObservable = ko.observable();
function activate() {
setup.currentViewName = router.activeRoute.name;
return refreshData();
}
var refreshData = function () {
myDataService.getSomeData(myObservable);
};
var viewModel = {
activate: activate,
deactivate: deactivate,
canDeactivate: canDeactivate
};
return viewModel;
});
You can also reveal literals, observables and even functions directly while revealing them -
title: ko.observable(true),
desc: "hey!",
canDeactivate: function() { if (title) ? true : false,
Check out durandal's router page for more info on what is available. Also, heads up Durandal 2.0 is switching up the router.
http://durandaljs.com/documentation/Router/

Add an activate function to your viewmodel as follows:
define([],
function() {
var vm = {
//#region Initialization
activate: activate,
//#endregion
};
return vm;
//#region Internal methods
function activate(context) {
var moduleId = context.routeInfo.moduleId;
var hash = context.routeInfo.hash;
}
//#endregion
});

Related

Durandal Composition Binding with canDeactivate

I am using Durandal 2.1, and I am having a problem with view composition. I have a view for managing many types of items. I also want a view to manage a subset of those types. So I created a manage view and a managesubset view. The managesubset view just composes the manage view and passes it an array containing the subset of items. This way the user can go to /100/manage or 100/managesubset where managesubset will only allow the user to manage a subset of items. I am using this pattern because I will have multiple different versions of managesubset.
My problem is that the canDeactivate method is not fired when going to managesubset. Is there anyway to fire the canDeactivate and Deactivate lifecycle events when composing?
According to #3 under Activator Lifecycle Callbacks here, I should be able to do this, but I cannot find any good examples.
Code:
manage.js
define(['durandal/app', 'plugins/router'], function (app, router) {
var constructor = function () {
var self = this;
//...variable creation and assignment
//life cycle events
self.activate = function (viewmodel) {
self.recordId(viewmodel.recordId);
self.assignableTypes(viewmodel.assignableTypes);
self.pageHeaderTitle = viewmodel.pageHeaderTitle;
self.pageHeaderIcon = viewmodel.pageHeaderIcon;
};
self.canActivate = function (id) {
var deferred = $.Deferred();
//check if user has access to manage equipment
};
self.canDeactivate = function () {
if (!self.saveSuccessfull() && this.isDirty()) {
return app.showMessage("You have unsaved changes, are you sure you want to leave?", "Unsaved Changes", ["Yes", "No"]);
}
else {
return true;
}
}
};
return constructor;
});
managesubset.js
define([], function () {
var recordId = ko.observable();
var manageRecord = ko.observable();
return {
recordId: recordId,
manageRecord: manageRecord,
activate: function (id) {
recordId(id);
manageRecord({
pageHeaderTitle: 'Manage Subset',
pageHeaderIcon: 'cb-subset',
assignableTypes: [102],
recordId: recordId()
});
},
canActivate: function (id) {
var deferred = $.Deferred();
//check if user has access to manage equipment
}
}
});
managesubset.html
<div data-bind="compose: { model: 'manage', activationData: manageRecord() }"></div>
The activate is called correctly each time. The deactivate and canDeactive are what don't work, and they are never called.

durandal, pass parameters to widget during navigation

i have several singleton views in my SPA, each of these view contain the same widget.
When the view is activated i take some parameters from the activate callback and pass it to the widget and it works fine.
But if i navigate the second time into the view (with different parameters into the activate callback)
the activate method of the widgets is rightly not raised.
How can i pass the fresh data to the widgets ?
I tried to make the parameter observable and subscribe it into the widget (settings.params.subscribe) and it works, but i don't think it's a good solution.
This should be pretty simple assuming you are returning a constructor from your widget -
View model -
var thisWidget = new widget(someArbitraryData)
function createWidget() {
dialog.show(thisWidget);
}
// later
function updateWidget() {
thisWidget.refreshData(newArbitraryData);
}
Widget module -
define([], function () {
var ctor = function () {
var self = this;
self.data = ko.observable();
};
ctor.prototype.refreshData = function (newData) {
var self = this;
self.data(newData);
};
ctor.prototype.activate = function (activationData) {
var self = this;
self.data(activationData);
};
});

Durandal.js 2.0 Set document title within activate method

In my shell, I have set up my routes like so:
router.map([
{ route: '', title: 'Search', moduleId: 'viewmodels/search/search' },
{ route: 'location/:paramX/:paramY', title: 'Location', moduleId: 'viewmodels/location/location' }
]).buildNavigationModel();
I have an activate method like so:
activate: function(paramX, paramY) {
// TODO: set document title
// TODO: do something with input params
}
For the location page, the document title is set to the Location | [Name of my app]. I would like to change this to be made up from the params taken in the activate method (paramX, paramY) on my activate method for the location page. How do I do this?
You can achieve this by overriding the default behaviour of the process of the router to set the title.
The title is always set after the navigation is complete so the activate method of your viewmodel has been called before. The current implementation in Durandal 2.0 is:
router.updateDocumentTitle = function(instance, instruction) {
if (instruction.config.title) {
if (app.title) {
document.title = instruction.config.title + " | " + app.title;
} else {
document.title = instruction.config.title;
}
} else if (app.title) {
document.title = app.title;
}
};
This is called in the method completeNavigation in the router.js.
In instance param you have the ViewModel that you are activating so a possible solution could be to override the updateDocumentTilte function in shell.js or main.js and use the instance to get the values that you want. For example you could do something like this (make sure you have the app and the router instance):
router.updateDocumentTitle = function (instance, instruction) {
if (instance.setTitle)
document.title = instance.setTitle();
else if (instruction.config.title) {
if (app.title) {
document.title = instruction.config.title + " | " + app.title;
} else {
document.title = instruction.config.title;
}
} else if (app.title) {
document.title = app.title;
}
};
In this code we check if the instance (the current ViewModel) contains a method setTitle, if it does then we get the title calling the function. Then in our viewmodel we can have something like:
define(function () {
var id;
var vm = {
activate: function (param) {
id = param;
return true;
},
setTitle: function () {
return 'My new Title ' + id; //Or whatever you want to return
}
};
return vm;
});
If your viewmodel does not contain this method, then it should fall to the current behaviour.
Here's how I achieved it:
activate: function (product, context) {
// Update the title
router.activeInstruction().config.title = "Buy " + product;
...
...
...
...
It works, but I don't know if that's the approved method.
I needed to use observables for this, because the data that the title is derived from is loaded by AJAX in the activate method.
So I put this in my application bootstrap code:
var originalRouterUpdateDocumentTitle = router.updateDocumentTitle;
router.updateDocumentTitle = function (instance, instruction) {
if (ko.isObservable(instance.documentTitle)) {
instruction.config.title = instance.documentTitle;
}
return originalRouterUpdateDocumentTitle(instance, instruction);
};
If the view model has an observable named documentTitle, it is copied to the instruction.config.title. This is then bound to the actual document.title by Durandal (using a subscription), so that whenever the value of the documentTitle observable changes, the document.title changes. The documentTitle observable could be a plain observable or a computed observable.
This approach also delegates most of the work to the actual router.updateDocumentTitle() method, by intercepting and modifying the instruction value based on instance, and then calling through to originalRouterUpdateDocumentTitle.
This works with Durandal 2.1.0.

Can I use Ext's loader to load non-ext scripts/object dynamically?

In my ExtJS 4.0.7 app I have some 3rd party javascripts that I need to dynamically load to render certain panel contents (some fancy charting/visualization widgets).
I run in to the age-old problem that the script doesn't finish loading before I try to use it. I thought ExtJS might have an elegant solution for this (much like the class loader: Ext.Loader).
I've looked at both Ext.Loader and Ext.ComponentLoader, but neither seem to provide what I'm looking for. Do I have to just "roll my own" and setup a timer to wait for a marker variable to exist?
Here's an example of how it's done in ExtJS 4.1.x:
Ext.Loader.loadScript({
url: '...', // URL of script
scope: this, // scope of callbacks
onLoad: function() { // callback fn when script is loaded
// ...
},
onError: function() { // callback fn if load fails
// ...
}
});
I've looked at both Ext.Loader and Ext.ComponentLoader, but neither
seem to provide what I'm looking for
Really looks like it's true. The only thing that can help you here, I think, is Loader's injectScriptElement method (which, however, is private):
var onError = function() {
// run this code on error
};
var onLoad = function() {
// run this code when script is loaded
};
Ext.Loader.injectScriptElement('/path/to/file.js', onLoad, onError);
Seems like this method would do what you want (here is example). But the only problem is that , ... you know, the method is marked as private.
This is exactly what newest Ext.Loader.loadScript from Ext.4-1 can be used for.
See http://docs.sencha.com/ext-js/4-1/#!/api/Ext.Loader-method-loadScript
For all you googlers out there, I ended up rolling my own by borrowing some Ext code:
var injectScriptElement = function(id, url, onLoad, onError, scope) {
var script = document.createElement('script'),
documentHead = typeof document !== 'undefined' && (document.head || document.getElementsByTagName('head')[0]),
cleanupScriptElement = function(script) {
script.id = id;
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
return this;
},
onLoadFn = function() {
cleanupScriptElement(script);
onLoad.call(scope);
},
onErrorFn = function() {
cleanupScriptElement(script);
onError.call(scope);
};
// if the script is already loaded, don't load it again
if (document.getElementById(id) !== null) {
onLoadFn();
return;
}
script.type = 'text/javascript';
script.src = url;
script.onload = onLoadFn;
script.onerror = onErrorFn;
script.onreadystatechange = function() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
onLoadFn();
}
};
documentHead.appendChild(script);
return script;
}
var error = function() {
console.log('error occurred');
}
var init = function() {
console.log('should not get run till the script is fully loaded');
}
injectScriptElement('myScriptElem', 'http://www.example.com/script.js', init, error, this);
From looking at the source it seems to me that you could do it in a bit of a hackish way. Try using Ext.Loader.setPath() to map a bogus namespace to your third party javascript files, and then use Ext.Loader.require() to try to load them. It doesn't look like ExtJS actually checks if required class is defined in the file included.

Passing config to ExtJS prototypes

I'm trying to figure out how ExtJS4 passes around config objects.
I want to do the equivalent of...
store = function(config){
if ( typeof config.call !== 'unndefined' ){
config.url = "server.php?c=" + config.call || config.url;
};
Sketch.Data.AutoSaveStore.superclass.constructor.call(this,config);
};
Ext.extend(store, Ext.data.Store{})
I am probably missing something obvious here, but having dug around in the sandbox file, the closest I have come is....
Ext.define('My.awesome.Class', {
// what i would like to pass.
config:{},
constructor: function(config) {
this.initConfig(config);
return this;
}
});
which doesn't seem to work if you do something like...
var awesome = Ext.create('My.awesome.Class',{
name="Super awesome"
});
alert(awesome.getName()); // 'awesome.getName is not a function'
However
Ext.define('My.awesome.Class', {
// The default config
config: {
name: 'Awesome',
isAwesome: true
},
constructor: function(config) {
this.initConfig(config);
return this;
}
});
var awesome = Ext.create('My.awesome.Class',{
name="Super awesome"
});
alert(awesome.getName()); // 'Super Awesome'
This is biting me in the rear end when trying to do complex store extensions.
Anyone have any idea how I pass a bunch of random params to the prototype?
You should not be using new operator to create new instance on your class. In ExtJS4, you should use Ext.create() method.
Try doing:
var awesome = Ext.create('My.awesome.Class');
alert(awesome.getName());
And if you want to pass some param when creating an instance, you can do the following
var awesome = Ext.create('My.awesome.Class',{name:'New Awesome'});