How to call a function of custom component from outside js file ?

Hi,

Let us assume , I am using below custom component :

webix.protoUI({
   name:"newComponent", // the name of a new component
   $init:function(config){ 
        this.load(data.xml)
        //functions executed on component initialization
   },
   defaults:{
      width:200,
      on:{'onItemClick' : function(){}} //attached events
   },          
   refresh_func:function(){
       var self = this;
        this.addChilView();

}, //any custom function
   $getSize: function(x, y){..}, 
   $setSize:function(x, y){..},
}, webix.ui.list, // the name of the base component
webix.Movable); // extended functionality

How can I call the function ‘refresh_func’ from a JavaScript file outside of where this custom component is defined ?

Is there anything like below I can do :

  $$('newComponent').refresh_func 

Thanks.

method 1:
create a global function (say “refresh_func”) and use it as refresh_func.call($$('newComponent'))

method 2:
create a mixin object

var myMixin = {
    refresh_func: function(){
        ...
   }
}

and in $init of the component

{
    $init: function(config){
        ...
        webix.extend(this, myMixin);
    }
}

or after object creation

webix.extend($$('newComponent'), myMixin);

and use $$('newComponent').refresh_func();

P.S.: just realized that you already defined this function in protoConfig.
this way you can use it anywhere without restriction.

Hi intregal,

I understood how you explained method1 and method2.

Just did not get what you mentioned in P.S

Yes, the function is deined in protoConfig, does that mean I can directly call it as $$(‘newComponent’).refresh_func(); from an other JS file. However, I have already done that but that is not working.

Thanks.

yes, you should be able to call it this way.
do you receive an error on call?

Yes, I am getting error as :smile:
'Cannot read property ‘refresh_func’ of undefined.

Just to add one more thing, in actual code it is not ‘refresh_func’ , it is ‘_refresh_func’. Can the _ make any difference ?

Thanks.

'Cannot read property 'refresh_func' of undefined.
looks like you have mixed webix.protoUI with webix.ui.
protoUI does not create an object, it creates ui type.
you need to use webix.ui to create an ui object.

var myNewComponent = webix.ui({
    view: "newComponent",
    id: "newComponent" //or any other which will be used in $$()
});
...
myNewComponent.refresh_func();
or
$$("newComponent").refresh_func();

but if you defined _refresh_func instead of refresh_func, then you have to call _refresh_func
P.S.: do not use functions starting with underscore if you are not sure what you do. as it may override webix’ private function and get minimized in production version.

Ok, thanks.

Helped me a lot to understand things.