gpt4 book ai didi

javascript - 每次导航到其子路由时,父路由器激活功能都会运行吗?

转载 作者:行者123 更新时间:2023-11-28 07:43:44 27 4
gpt4 key购买 nike

这可能是代码结构的问题,而不是框架的问题。

基本上我想知道每次导航到其子路由之一时是否应该调用父路由器上的激活函数?

我的目标:有一个返回子路由器的模块,这是父路由器。如果用户添加新内容,则该父路由器负责创建对象;如果用户选择已经存在的内容,则该父路由器负责从服务器检索数据。子路由模块只需获取通过父路由模块创建或检索的对象,并提供表单输入来操作该对象(通过 ko 数据绑定(bind))。我遇到的问题是每次子路由导航到时都会调用父路由器的激活函数,这是创建/检索逻辑所在的位置,并导致再次检索对象,从而导致任何数据操作被覆盖。

下面是一些代码,希望能更好地说明:

// ParentRouter
define([...], function(...) {
var selectedObj = ko.observable(null),
configRouter = router.createChildRouter()
.makeRelative({
moduleId: 'viewmodels',
fromParent: true,
dynamicHash: ':id'
}).map([
{
route: ['Settings 1', ''],
moduleId: 'SettingsOne',
nav: true
},
{
route: 'Settings 2',
moduleId: 'SettingsTwo',
nav: true
},
{
route: 'Settings 3',
moduleId: 'SettingsThree',
nav: true
}
]).buildNavigationModel();

function getSelectedObj() {
return selectedObj;
}

return {
router: configRouter,

obj: selectedObj, // privileged property which is accessed by other modules via the getSelectedObj method, this prop gets set in the activate function depending on the param
getSelectedObj: getSelectedObj, // method which returns the current selected obj

activate: function (objId) {

if (objId == 'New') {

// create a new object with default props

} else {

// retrieve the data for the selected obj from API via the 'objId' param

}

}
}
});



// SettingsOne module - child route module

define(['viewmodels/parentRouter'], function(parentRouter) {

// this module simply gets a property from the parent routers module and binds it to form inputs in its View (which update automatically) so the user can edit information on that obj


var obj = parentRouter.getSelectedObj(); // get the current selected obj via parent routers module method

return {
obj: obj
}
});


Below is the shell module of my app, showing the main application router.
// Shell.js
define([
'plugins/router'
], function (router) {
var routes = [
{
route: '',
moduleId: 'viewmodels/home'
},
{
route: ':id*configs',
moduleId: 'viewmodels/parentRouter'
}
];

return {
router: router,
activate: function () {
return router.map(routes)
.mapUnknownRoutes('viewmodels/notfound', 'not-found')
.activate();
}
}
});

最佳答案

我认为每次在激活 child 之前激活 parent 没有什么问题。如果您不希望再次发生检索,请将其设置为有条件的,例如:

define(function (require) {
var
$ = require('jquery'),
Q = require('q'),

activate = function () {
return load();
},

loadPromise = null,

load = function () {
return loadPromise || (loadPromise = Q($.get('/my/api'))
.then(function (data) {
//use data;
}));
};

return {
activate: activate
}
});

关于javascript - 每次导航到其子路由时,父路由器激活功能都会运行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27691812/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com