Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackboneJS: How to call function outside view from view's events hash?

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!

like image 508
MattM Avatar asked Dec 11 '13 19:12

MattM


2 Answers

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.

like image 66
Cristi Mihai Avatar answered Oct 24 '22 06:10

Cristi Mihai


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);
    }
});
like image 29
Sushanth -- Avatar answered Oct 24 '22 07:10

Sushanth --