从基础视图自动扩展事件
我有一个用于所有视图的基类,然后在应用程序的每个部分(如配置文件)中,我也有一个基类。这样,共享模板和属性就可以在我的应用程序的多个层面上使用。
我知道,如果您将 Backbone 视图中的事件属性设置为函数而不是对象文字,它将为您实例化,但我不确定如何利用它来发挥我的优势。我的问题是,自动扩展在基本视图中创建的事件的最佳方法是什么。
我知道一种可能性,我在视图初始化时获取基本事件类并将当前事件扩展到它,但这似乎有点老套,我必须在每个视图上复制此代码。如果您知道更好的方法请分享。
谢谢。
I have a base class for all views and then in each section of the app, like profiles, I also have a base class. That way shared templates and properties can be used throughout my app on many levels.
I know that if you make the event property in a Backbone view a function instead of an object literal, it will be instantiated for you, I'm not sure how to use this to my advantage, though. My question is, what's the best way to automatically extend events created in a base view.
I know one possibility where I, on view initialize, fetch the base event class and extend my current event on to it, but it seems a little hacky, and I would have to duplicate this code on every view. If you know a better way please share.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它并不是什么都不做,但这是迄今为止我见过的最简单的方法。
我还用我一直使用的另一种方式创建了一个要点: https://gist.github.com/1271041
It's not doing nothing, but it's the simplest way I've seen so far.
I've also created a gist on another way I've been using: https://gist.github.com/1271041
以下是我在子视图中扩展父视图事件的方法:
注意:这只适用于 Backbone 0.5.3。在该版本之前,您无法将事件定义为函数。
Here's how I extend the parent view's events in my child view:
Note: this only works as of Backbone 0.5.3. Before that version, you couldn't define events as a function.
我相信JohnnyO的答案是最好的。不过,我遇到了另外两种方法,我将它们粘贴在这里。
遗憾的是,没有一种“自动”解决方案不需要在每个新视图中额外手写代码,但事实就是如此。
作者:Paul - backbone.js 视图继承。父级中的“this”解析
我不知道您可以在 Backbone.view.extend 中提供构造函数方法。很高兴知道。
作者:rulfzid - Sub Class a Backbone.View Sub Class &保留事件
我已经设想(并拒绝)这种方法,但这种方法有一个额外的变化,即将您的基本事件称为其他名称,以便“genericEvents 不会覆盖任何事件”,正如作者所说。除非他正在谈论对您在两个事件对象内部传递的两个事件的某种修改,否则我不确定他在说什么,我只是使用 proto 或原型来引用父母事件。但同样,很高兴知道。
I believe JohnnyO's answer is the best. However I came across two other ways of doing it and I'll paste them here.
It's a pity that there is no "automatic" solution that doesn't require additional hand-written code in each new view, but it is what it is.
By Paul - backbone.js view inheritence. `this` resolution in parent
I didn't know you could provide a constructor method in your Backbone.view.extend. Good to know.
By rulfzid - Sub Class a Backbone.View Sub Class & retain events
I had already envisioned (and declined) this approach but this one has the added twist of calling your base event something else so that "genericEvents don't overwrite any events" as the author says. Unless he's talking about some kind of munging of both events you're passing inside of both events object, I'm not sure what he's talking about, I'd just use proto or prototype to reference the parents events. But again, good to know.