As an example, here's what I'm looking to do...
function doSomething(customParameter) {
console.log(customParameter);
}
var MyView = Backbone.View.extend({
// Other view stuff, skipping it...
events: {
'click .someClass': doSomething(customParameter)
}
});
The motivation here is I want to be able to pass variables (local to the view) to some other function outside the view. The reason I want to do this is so that the "other function" is only written once and not four times...it would seriously save my project over 100 lines of code.
After much googling I haven't found a solution to this...any ideas?
Thanks!
Here is one way of doing it:
function doSomething(customParameter) {
console.log(customParameter);
}
var MyView = Backbone.View.extend({
// Other view stuff, skipping it...
events: {
'click .someClass': function(ev) { doSomething(this.customParameter); }
}
});
In this example, you declare a function that passes the arguments needed from the local view to that doSomething
method.
Another way could be to call the doSomething() with the context of the current view, if you don't want to pass all the required arguments:
function doSomething(ev) {
console.log(this.customParameter); // here, the context this will be the view.
}
var MyView = Backbone.View.extend({
// Other view stuff, skipping it...
events: {
'click .someClass': function(ev) { doSomething.call(this, ev); }
}
});
A more OOP approach would be to have a base View for that common code:
var MyBaseView = Backbone.View.extend({
doSomething: function(ev) {
console.log(this.customParameter);
}
});
var MyView = MyBaseView.extend({
extends: {
'click .someClass': 'doSomething'
}
});
Probably there are more ways of doing it, you just have to see which scenario applies best to your needs.
You can try calling a method that is internal to the view which calls the method in question
var MyView = Backbone.View.extend({
// Other view stuff, skipping it...
events: {
'click .someClass': 'callSomething'
},
callSomething: function() {
doSomething(customParameter);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With