Backbone.js - 在哪里定义视图助手?
最近几周我一直在尝试 Backbone.js 并进行尝试,所以有点菜鸟问题......
在backbone.js 中定义和使用视图助手的“正确”方法是什么?
据我所知,定义在模板中使用的助手的唯一真正位置是模型或集合本身。然而,当该帮助器直接返回 HTML 时,这开始感觉有点脏。
有更好的办法吗?
I've been kicking the tyres of Backbone.js and having a play around in recent weeks, so a bit of a noob question...
What is the 'correct' way to define and use view helpers in backbone.js?
As far as I can work out, the only real place to define helpers to use in your templates is on the model or collection itself. However, when that helper is directly returning HTML, this begins to feel a little dirty.
Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我在 Backbone.js 中放置视图助手的几个不同位置:
如果该助手特定于某个视图,请将其放在视图定义中的右侧:
如果将使用该助手通过所有视图,扩展 Backbone View 类,以便所有视图继承此功能:
如果您需要在视图之间共享更复杂的助手,请让视图相互扩展:
我不确定什么是最佳实践(或者是否有既定的最佳实践)实践),但这些模式看起来相当干净并且运行良好。
There are a few different places that I put view helpers with Backbone.js:
If the helper is specific to a certain view, put it right in the view definition:
If the helper will be used by all views, extend the Backbone View class so that all views inherit this function:
If you need more complicated sharing of helpers between views, have views extend each other:
I'm not sure what is best practice (or if there is an established best practice), but these patterns seem fairly clean and work well.
当您构建更大的 Backbone 应用程序时,您可能希望为所有内容命名。然后你就会有一个全球助手的位置。我还没有完成完美的命名空间设置。但现在我正在做这样的事情:
我的视图类看起来像这样:
我的控制器是实例化新视图的对象(并在
currentView
中放置一个引用。记住,您应该始终删除最后一个视图)视图,以便以前的视图事件全部解除绑定,并减少内存使用量。As you build bigger Backbone apps, you'll probably want to namespace everything. Then you will have a place for global helpers. I haven't made the perfect namespace setup yet. But right now I'm doing something like this:
My view classes look something like this:
My controller is the object that instantiates new views (and places a reference in
currentView
. Remember you should always remove your last view so the previous views events all get unbinded and your reduce memory usage.快速解决方案(CoffeeScript)
然后您可以在您的视图中使用它:
Quick solution (CoffeeScript)
Then you can use that in your view: