gpt4 book ai didi

javascript - Backbone.js 中主从场景的首选模式

转载 作者:行者123 更新时间:2023-11-30 05:56:23 25 4
gpt4 key购买 nike

大多数处理主从场景的 Backbone 教程通过使用从路由传递的模型创建新 View 来处理细节状态(example)。我想知道备选方案的优缺点是什么。

关于这种实例化新 View 的方法,一直让我印象深刻的是,它似乎错失了使用 Backbone 的模型- View 绑定(bind)的机会。即,创建一个根据所选模型更新的详细信息 View 。但这将需要一个仅与 UI/事件状态相关的单独模型。

我可以想到三种不同的模式:

  • 为每个事件细节创建/销毁 View 。 (这似乎是多余的工作,更不用说潜在的 zombie problems )
  • 维护一个表示事件细节的附加模型,并创建一个在模型更新时重新呈现自身的 View
  • 使用交换关联模型的方法创建一个 View (我认为这会导致事件绑定(bind)问题,可能不是一个好主意)

在像上面链接的示例教程这样的简单案例的上下文中,优点/缺点是什么? #2 中使用 UI 模型的想法是一种不好的做法吗?还有其他解决方案吗?

最佳答案

根据我的经验,UI 模型非常有用。我们为应用程序中的每个“页面”维护一个 ContextModel。真正好的是我们保证“页面”使用完整的 ContextModel 进行初始化,因此只有一个地方最初创建了上下文。

我们的 AppView 总是在触发特定路由时为页面创建初始上下文。路由处理程序将设置上下文的默认值,并从路由的值中解析内容。

一旦页面本身被初始化,它只需要担心 ContextModel 的变化,并有处理程序进行任何必要的更新,然后更新路径。

这是一个直接从我们的 AppView 中提取的示例:

onSomeRoute : function (project, category, pivot, tab, item) {

// Setup page context with defaults.
var options = {
category : 'traits',
tab : 'population',
item : null
};

// Figure out what the allowed categories and tabs are from this
// environment by checking against all schema items.
[snipped]

// Resolve the `category` and the `pivot`. Try and match the pivot's
// slug, else choose the first pivot in the category.
if (_(categories).contains(category)) options.category = category;

[snipped]

if (pivots) options.pivot = pivots.find({ slug : pivot }) || pivots.first();

// Resolve the `tab` and `item`. Only allow valid tabs, and then try
// to match the item's slug as well, or choose the first one.
var tabs = ['population', 'sources', 'engagement', 'retention'];
if (_(tabs).contains(tab)) options.tab = tab;
[snipped]

// Now that we've applied some defaults, make sure the path is
// updated to reflect what the interface is showing.
[snipped]

this.loadPage('some-page', options);
}

然后在相关的 PageView 中,我们有几个更改处理程序:

// When category changes, try to match the current pivot against pivots
// in the category, else choose the first pivot from the category.
onCategoryChange : function (context, category) {
var schema = this.context.get('environment').get(category);
if (!schema.contains(this.context.get('pivot')))
this.context.set('pivot', schema.first());

this.router.update({
category : category
});
},

// When the pivot changes, create a new set of segments for the context.
onPivotChange : function (context, pivot) {
Segmenter.segment(context, function (segments) {
context.get('segments').reset(segments).each(function (segment) {
segment.evaluate();
});
});

this.router.update({
pivot : pivot.get('slug')
});
},

请注意,所有更改处理程序都会根据上下文中的更改来更新页面的 URL。 (我们在路由器上编写了几个自定义方法,使这对我们来说真的很容易。)但它们也执行我们需要为页面发生的任何其他逻辑。

希望其中的一些内容能给您一些想法。通常,存储在 URL 中的任何状态都在我们的 PageContext 中,然后为了方便起见,从该状态派生的其他一些东西也存储在那里。

关于javascript - Backbone.js 中主从场景的首选模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11605193/

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