gpt4 book ai didi

javascript - 为什么 HotTowel SPA 模板中有单独的激活和启动功能?

转载 作者:行者123 更新时间:2023-12-02 17:58:17 24 4
gpt4 key购买 nike

John Papa 的 HotTowel SPA 模板中导航模板的设置方式是,在 shell.js 中传递给 Durandal 的 activate 方法是一行(见下文)。这是我不知道的一些 Javascript 模式吗?不只是将启动代码包含在激活本身中的原因是什么?

    var shell = {
activate: activate,
router: router
};

return shell;

//#region Internal Methods
function activate() {
return boot();
}

function boot() {
log('HotTowel Loaded!', null, true);

router.on('router:route:not-found', function (fragment) {
logError('No Route Found', fragment, true);
});

var routes = ...

最佳答案

在您的代码示例中,boot 是一个匿名函数,在 activate 方法中调用它之前不会对其进行求值。 Durandal 在检查 canActivate 方法后调用 activate 方法。这是 View 模型的任何初始化代码都可以运行的地方(加载数据、枚举或启动)

上述代码的作者可能认为,为了演示如何使用 activate,最好从那里调用匿名函数。

示例

例如,让我们添加一些密集的console.log'ing,让用户确切地知道发生了什么

define([], function () {
var shell = {
activate: activate,
router: router
};

return shell;

//#region Internal Methods
function activate() {
var user = showUserName();
initializeVM(user);
return boot();
}

function showUserName() {
var thisUser = 'You';
log('User is + thisUser +'!', null, true);
return thisUser;
}

function initializeVM(user) {
log('Initializing ' + user + '!', null, true);
}

function boot() {
log('HotTowel Loaded!', null, true);

router.on('router:route:not-found', function (fragment) {
logError('No Route Found', fragment, true);
});
}
});

显然,我们实际上并没有对这些功能做任何事情,但了解它们要突出显示的内容正是我们所追求的。假设我们想要获取一个用户,然后使用该用户初始化 View 模型,然后实际启动我们的应用程序以显示第一条路线,这是我们可以做到的一种方法。通过将函数(方法)分离成它们自己的匿名函数,您可以完成一些事情 -

  1. 分离关注点 - 该函数仅执行其所需任务的一小部分,而不是使用一个包含所有代码的大型函数。
  2. 允许随着应用程序的扩展进行代码组织 - 您可以轻松地将这些函数移动到一个模块中,该模块旨在处理分离出来的某些内容,尤其是使用 Durandal 和 require.js
  3. 您可以更进一步,实际上进行数据调用,返回一个 promise ,以阻止应用程序启动,直到进行身份验证或执行其他操作。

相反且更丑陋的代码是这样的 -

define([], function () {
var shell = {
activate: activate,
router: router
};

return shell;

//#region Internal Methods
function activate() {
var thisUser = 'You';
log('User is + thisUser +'!', null, true);
log('Initializing ' + user + '!', null, true);
log('HotTowel Loaded!', null, true);

router.on('router:route:not-found', function (fragment) {
logError('No Route Found', fragment, true);
});
}
});

现在上面的函数中没有大量代码,但想象一下如果每个函数都有 10 行代码 - 它很快就会变得困惑。

因此,回答你的问题并不一定是 JavaScript 特定的模式,它只是组织代码时的更好实践。如果您遵循作者整理的一些 PluralSight 教程,他通常将其称为模块化代码 (ravoli) 与一堆代码 (spaghetti)

关于javascript - 为什么 HotTowel SPA 模板中有单独的激活和启动功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20806176/

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