i was wondering how to use functions within the Backbone.View code. Can someone advise/show me how this is done properly. I understand that extending is only put into the var. I've looked at extend, prototype, super, parent, baseview and other fancy stuff. But that only confused me even more ;).
var jsHelpers = {
intVar: 300,
sum: function(a, b, callback) {
// do something interesting:
c = a + b;
d = c + intVar;
callback(c);
} //end sum function
} //end jsHelpers
/* somewhere else */
ViewThingy = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
var result = jsHelpers.sum(1, 1, function(callbackData) {
//let's do something with the return stuff:
this.$el.html(callbackData);
}); //end jsHelpers
} // end render
}); //end extend
The error is of course that the function jsHelpers.sum();
is not available in the extend
.
TIA ! Vince
var View = Backbone.View.extend({
hello: function() {
console.log('hello');
},
// You can also override Backbone methods here.
initialize: function() {
// Do init code shared by all your views
}
});
// All the views in your app should extend off this view instead of Backbone.View.
var RandomView = View.extend({
initialize: function() {
// Call the parent to do init code.
View.prototype.initialize.apply(this, arguments);
this.hello();
},
// You can override methods too..
hello: function() {
// You can call the parent.
View.prototype.hello.apply(this, arguments);
}
});
Actually it is a good idea to always extend View, Model, Collection and Router when you make an app as there will always be shared functionality you want to do to not repeat the same code everywhere in your app. Typically for a view this would be stuff like the render routine such as rendering the template and rendering sub views - you wouldn't want to do that logic again in every view in your app.
Typically to share other code you would use a dependency manager like RequireJS or Browserify. But you can also have a single global object:
window.app = {};
and attach things to it:
window.app.utils = ....;
That is accessible from anywhere. Having an app object is pretty common - e.g. you would often have a Model that maintained the state of the app at app.state
.