I am currently working on a Backbone JS application, and I started using Browserify for the first time. But of course I ran into a few problematics. This is one of them.
I have the following module, /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')
.
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?
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.
Is it me who do not understand Browserify properly, and is there a more clever solution? 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. Think of it as a reference or using statement. See this SO post for more details.
But with router = new Router();
you run into a problem of your router
being instanced. I suggest that in Router.js
you export an instance of your router
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.