[英]Backbone.js and Browserify - requiring same module multiple times
I am currently working on a Backbone JS application, and I started using Browserify for the first time. 我目前正在开发Backbone JS应用程序,并且第一次开始使用Browserify。 But of course I ran into a few problematics.
但是我当然遇到了一些问题。 This is one of them.
这就是其中之一。
I have the following module, /js/views/Home.js
. 我有以下模块
/js/views/Home.js
。
var $ = require('jquery'),
_ = require('underscore'),
Backbone = require('backbone');
Backbone.$ = $;
module.exports = Backbone.View.extend({
el: '#view',
template: _.template($('#home-template').html()),
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template());
},
events: {
'click button': 'searchSubmit'
},
searchSubmit: function () {
// this should be where the magic happens
}
});
When the searchSubmit
method is called, I want to do something like router.navigate('search')
. 调用
searchSubmit
方法时,我想做类似router.navigate('search')
事情。
My question: If I have a router module, Router.js
, do I then need to create a new instance of it in all of my modules every time I want some router functionality? 我的问题:如果我有一个路由器模块
Router.js
,那么我每次需要一些路由器功能时是否需要在所有模块中创建一个新实例?
var Router = require('./Router.js'),
router = new Router();
It just does not seem logical to create a new router in every view, when Browserify bundles them all together. 当Browserify将它们全部捆绑在一起时,在每个视图中创建一个新路由器似乎并不合逻辑。
Is it me who do not understand Browserify properly, and is there a more clever solution? 是我不正确理解Browserify的人,还有更聪明的解决方案吗? Thanks!
谢谢!
When you call 你打电话时
var Router = require('./Router.js');
Browserify is actually keeping track of a single instance of Router
, so it is not a new instance every time. Browserify实际上是在跟踪
Router
的单个实例,因此它并非每次都是新实例。 Think of it as a reference or using statement. 可以将其视为参考或使用声明。 See this SO post for more details.
有关更多详细信息,请参见此SO帖子 。
But with router = new Router();
但是使用
router = new Router();
you run into a problem of your router
being instanced. 您遇到
router
实例化的问题。 I suggest that in Router.js
you export an instance of your router
. 我建议您在
Router.js
导出router
的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.