Pass data in DurandalJS to other view

元气小坏坏 提交于 2019-12-04 19:25:05

As far as I know, the only seamless way to pass parameters between view models in a Durandal app is to use the normal hash-based url parameters.
In you example, you can define a router that takes a orderId and repairOrder parameters, then your url would look something like this: http://localhost:60312/#/page/2/2

This is best option, if your data isn't too sensitive. Leave the navigation parameters in the open, and handle the values with care in the second view model. In other words, design your view model so that it can properly handle any values - even if a user directly modifies a parameter value, your view model should be able to handle it correctly.

It can be advantageous to be able to set url parameters directly, but you do have to be careful to ensure the integrity of the values before consuming them.

However, if you need to hide the parameters, you do have some different options:

Encryption: Use an encryption library like tea.js, and encrypt the value before adding it as a parameter value for navigation. Then, of course, decrypt it on the second page before using it. This allows Durandal's router navigation to work normally, while preventing users from supply their own values.

If you really need to prevent users from entering their own values, and you can bear the overhead of a few extra KB's, this is a good approach as long as you only need to pass a few parameters.

Shared data model: Use a singleton model which is shared between the two view models. This model can be manually required() as needed, and essentially serves as a repository for the application state that is shared between one or more view models. This works fine, but it's kind of like having a big global variable - it can get messy if it's overused.

Modify VM directly: (Only for singleton view models) Manually require() the second view model and set its properties before navigating to it.

I would like to add something to the very good @Joseph Gabriel answer. In durandal you can do this:

router.map( url: 'page2/:orderid/:repairorder',
            name: 'Page2',
            moduleId: 'viewModels/page2');

http://localhost:60312/#/page/2/2

But also, you can do this:

router.map( url: 'page2',
            name: 'Page2',
            moduleId: 'viewModels/page2');

http://localhost:60312/#/page2?orderid=2&repairorder=2

You don't nedd to specify all the parameters that you are pasing. Yo can get this parameters from the input of the active method.

var activate = function(context) {
  console.log(context.orderid);
  console.log(context.repairorder);
}

Sometimes the second solution can be more appropriated if you want that the user can store the url to repeat a query only copping that in the browser.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!