初始化主干视图时
如何才能在每次初始化backbone.js 视图时运行一个函数?
我正在寻找可以放在正常视图代码之外的东西,作为backbone.js 的扩展。
这个想法是减少样板文件的数量。
How do I make it so that a function runs every time a backbone.js view is initialized?
I'm looking for something that I can put on outside of my normal view code, as an extension to backbone.js.
The idea is to reduce the amount of boilerplate.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于 Javascript 不是真正的面向对象编程语言,因此您不能像 java 或 c# 那样使用继承来解决问题。
一种可能的解决方案是使用工厂设计模式。
您可以调用工厂方法来实例化视图,而不是直接实例化视图。
这是一个 jsfiddle 示例
它不是其他语言可能的优雅解决方案,但它确实工作。
Since Javascript is not a true object oriented programing language, you can't use inheritance to solve your problem as you could if it was java or c#.
One possible solution is to use the factory design pattern.
Instead of instantiating your view directly, you can call a factory method that will instantiate your view.
Here's a jsfiddle example
It's not as an elegant solution that is possible with other languages, but it does the job.
使用内置的backbone.js初始化函数:
http://documentcloud.github.com/backbone/#视图构造函数
编辑:我应该更清楚。
用 Patrick Ewing 的话说,这里http://podcast.rubyonrails.org/programs /1/episodes/railsconf-2007:
“如果它像鸭子一样走路并且像鸭子一样说话,那么它就是一只鸭子,对吗?所以如果这只鸭子没有给你你想要的噪音,你必须打那只鸭子,直到它返回你所期望的“
Duck Punch(或 Monkey Patch,如果你愿意)Backbone 对象。
use the builtin backbone.js initialize function:
http://documentcloud.github.com/backbone/#View-constructor
EDIT: I should be more clear.
In the words of Patrick Ewing found here http://podcast.rubyonrails.org/programs/1/episodes/railsconf-2007:
"if it walks like a duck and talks like a duck, it’s a duck, right? So if this duck is not giving you the noise that you want, you’ve got to just punch that duck until it returns what you expect"
Duck Punch (or Monkey Patch if you prefer) the Backbone object.
您可以使用 Backbone.Events。
在应用程序的顶层或全局对象上:
在您想要触发函数的任何视图的初始化方法中:
其中“this”是作为“view”参数传递给函数的视图实例。
You can use Backbone.Events.
On the top level of your app or on the global object:
And in the initialize method of any view you want to trigger your function:
where "this" is the view instance passed as the "view" parameter to your function.