【发布时间】:2010-12-10 18:41:56
【问题描述】:
我越来越喜欢backbone.js。我希望给定模型有多个视图:
- 一个列表视图,其中每个模型都有一个带有自己的 li 元素的视图。
- 显示模型所有详细信息的详细视图。
我的问题是,我正在寻找一种允许一种观点与另一种观点交流的好方法,并选择了以下方法:
/** Allow a model to keep track of it's views. **/
Backbone.Model.prototype.addView = function (view) {
// Ensure our model has a view array.
if (typeof this.views === 'undefined')
{
this.views = [];
}
// Append our newest view to the array only if it is not already present.
if (_.indexOf(this.views, view) === -1)
{
this.views.push(view);
}
}
/** Allow a model to remove all of it's views.
*
* @param {Object} args Any arguments will be provided to the view's method.
*/
Backbone.Model.prototype.unloadViews = function (args) {
var n = (typeof this.views === 'undefined') ? 0 : this.views.length;
for (var i = 0; i < n; i++)
{
var view = this.views[i];
if (typeof view.unloadView === 'function')
{
view.unloadView(args);
}
}
}
/** Allow a model to re-render all of it's views.
*
* @param {Object} args Any argyments will be provided to the view's method.
*/
Backbone.Model.prototype.renderViews = function (args) {
var n = (typeof this.views === 'undefined') ? 0 : this.views.length;
for (var i = 0; i < n; i++)
{
var view = this.views[i];
if (typeof view.render === 'function')
{
view.render(args);
}
}
}
我的问题
- 我在学习backbone.js 的过程中是否遗漏了一些可以让我自然地做到这一点的东西?
- 我是否有理由避免这种情况?
其他信息
我已在 GitHub 上分享了该应用程序(非常初级):https://github.com/aarongreenlee/Learning-backbone.js。如果您希望在该环境中查看代码,可以在此处访问它:https://github.com/aarongreenlee/Learning-backbone.js/commit/ea4e61d934d2f987726720e81c479f9d9bb86e09#diff-2(初始提交)。
感谢您的宝贵时间和帮助!
【问题讨论】:
-
+1 让我开始使用 Backbone.js。