How to effect the @Override of a Function in Angularjs?

Asked

Viewed 327 times

1

I have an abstract controller with Angularjs.

In it I have among other things, a research Toolbar.

I would like to use this search input on all controllers that inherit from the parent controller. being triggered through an "ng-change".

function IndexCtrl() {
  var vm = this;
  //Objects
  vm.searchText = '';

  //Methods
  vm.search = search;

  function search(search) {

  }
}

function TesteCtrl() {
    var vm = this;

    //Methods
    vm.search = search;

    function search(search) {
      console.log(search);
    }
}

What implementation alternatives do I have, when ng-change from the parent controller is triggered, the child controller method is triggered (when in use)?

1 answer

0

An alternative to solve your problem would be to use overload.

Ex: Overload - Number of parameters

Once again I will use Js "apply" method to solve this question, as the language moves a lot with prototypes and constructors, nothing more intelligent than using this scope method. The idea I had was to use a function as a function and at the same time as an object that holds its own properties.

var Person = {
Class: function(){  
    //Private
    var name = ''

    //Public
    this.name = function(){
        return this.name[ arguments.length ].apply( this, arguments )
    }

    this.name[0] = function(){ return name }
    this.name[1] = function(n){ name = n }
    this.name[2] = function(a, b){ name = a + " " + b }
    }   
}

Here I create a function ( method ) with name "name" and create 3 more properties of it that are: 0, 1 and 2. They are numbers, but still are properties of the name method. What the main function will do is see how many parameters it has and will call its corresponding property, which is nothing more than another method that will be executed in the same context as the name and will have the same parameters as the name.

Soon:

var Edu  = new Person.Class

Edu .name() //  ''
Edu .name('Eduardo') 
Edu . name() // "Eduardo"
Edu . name('Eduardo', 'Ottaviani')
Edu . name() // "Eduardo Ottaviani"

It is not because I had this idea not, but I consider this the most elegant form of operator overload so far. Perhaps it is not the most efficient, I have not tested its speed in relation to other techniques. If it is slower, I believe it is not noticeable.

Source.: https://javiani.wordpress.com/2010/04/17/overload-em-javascript/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.