user101289
user101289

Reputation: 10422

Calling a mootools class method from another external function

I've got a legacy mootools class I'm using that has many functions. Instead of extending the class, I'm trying to simply call one of the class methods from outside the class. So if the class looked something like this:

var myClass = new Class({
    search: function(){
        this.searchSpinner.show();
        this.request.send({data: this.data});
    },

    // many other functions
})

I need to call the search method from another script loaded on the same page.

Right now I'm trying like this:

window.myClass.search();

But this results in a big hairy error that I can't make sense of but which looks like:

Uncaught TypeError: Object function (){e(this);if(g.$prototyping){return this;}this.$caller=null;var i=(this.initialize)?this.initialize.apply(this,arguments):this;this.$caller=this.caller=null;
return i;} has no method 'search' 

Is there a 'right' way to call this method?

Upvotes: 0

Views: 735

Answers (2)

Romain
Romain

Reputation: 810

You are trying to apply a "singleton" pattern : if you will be using only one occurrence of this class, you can use :

var mySingleton = new new Class({

(notice the 2 x new keyword) then

mySingleton.search()

to call it...

oh and if you trying to add static functions to a mootools class, just declare them like that :

var myClass = new Class({ });
myClass.staticMethod = function() {
    // ...
};

hope this helps !

Upvotes: 1

Julian H. Lam
Julian H. Lam

Reputation: 26124

A class as defined using Mootool's Class does not behave quite like a static class in other languages. In order to access methods in that class, you'll have to create an instance of that class first:

var classObj = new myClass(/*any parameters if required, check the "initialize" method*/);
classObj.search();

Upvotes: 3

Related Questions