Showing posts with label component. Show all posts
Showing posts with label component. Show all posts

Thursday, February 20, 2020

ReactJS Call Methods / Functions Between Component And Layout

In order to execute a function from a layout / component, you will need to pass component / layout reference to other side. React supports a special attribute that you can attach to any component, pass reference to other side, and you can access the functions of the component in the layout accessing
Sample App.js
import React, { Suspense, lazy } from "react";
import { BrowserRouter, Switch } from "react-router-dom";
import DashboardLayoutRoute from "./DashboardLayout";

import Home from "./Home";

const Connections = lazy(() => import("./Connections"));

class App extends React.Component {
  constructor() {
    super();

    console.log("App Initialized");
  }

  render() {
    return (
      <BrowserRouter basename={this.APP_PATH}>
        <Switch>
          <DashboardLayoutRoute exact path="/" component={Home} />
        </Switch>
        <Suspense fallback={<div>Loading...</div>}>
          <Switch>
            <DashboardLayoutRoute path="/connections" component={Connections} />
          </Switch>
        </Suspense>
      </BrowserRouter>
    );
  }
}

export default App;
Sample Layout
import React from "react";
import { Route } from "react-router-dom";

class DashboardLayoutComponent extends React.Component {
  constructor(props) {
    super(props);

    this.callBackToComponent = this.callBackToComponent.bind(this);
  }

  componentDidMount() {
    console.log("Layout Component Did Mount");
    let _this = this;
    if (this.props.children.type._result instanceof Promise) {
      this.props.children.type._result.then(function(data) {
        _this.callBackToComponent();
      });
    } else {
      this.callBackToComponent();
    }
  }

  componentDidUpdate() {
    console.log("Layout Component Did Update");
    let _this = this;
    if (this.props.children.type._result instanceof Promise) {
      this.props.children.type._result.then(function(data) {
        _this.callBackToComponent();
      });
    } else {
      this.callBackToComponent();
    }
  }

  callBackToComponent() {
    let t = this.props.children.type;
    if (t.prototype !== undefined) {
      t.prototype.callBackToParentComponent(this);
    } else {
      // If you use your Route in Suspense
      t._result.prototype.callBackToParentComponent(this);
    }
  }

  callbackParent() {
    console.log("Layout function called from some component");
  }

  render() {
    return (
      <div className={"dashboard-main-container"}>
        <div className="container">
          <div className="row">
            <div className="col-sm-10 right-body-container">
              {this.props.children}
            </div>
          </div>
        </div>
      </div>
    );
  }
}

const DashboardLayoutRoute = ({ component: Component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={matchProps => (
        <DashboardLayoutComponent {...matchProps}>
          <Component key={matchProps.match.params.id} {...matchProps} />
        </DashboardLayoutComponent>
      )}
    />
  );
};

export default DashboardLayoutRoute;
Sample Component
import React from "react";
import { Link } from "react-router-dom";

class Connections extends React.Component {
  constructor() {
    super();

    console.log("Connections");
  }

  // this function will be called from layout function with self reference
  // so calling [layout.callbackParent()] will call a function inside layout component itself
  callBackToParentComponent(layout) {
    console.log("callBackToParentComponent for Connections");
    layout.callbackParent();
  }

  render() {
    return (
      <div>
        <h1>Connections</h1>
        <Link to={"/"}>Home</Link>
      </div>
    );
  }
}

export default Connections;
Sample console.log
App Initialized 
App Initialized 
Layout Component Did Mount 
callBackToParentComponent for Connections 
Layout function called from some component 
Connections 
Connections 
Home 
Home 
Layout Component Did Mount 
callBackToParentComponent for Home 
Layout function called from some component 
Connections 
Connections 
Layout Component Did Mount 
callBackToParentComponent for Connections 
Layout function called from some component 
Sample Output:
Live Example At codesandbox.io:

https://codesandbox.io/s/reactjs-call-methods-functions-between-component-and-layout-fydou

Thursday, May 18, 2017

AngularJS How to call controller function from outside of controller component

Its not a good practice to call AngularJS function from outside of its scope. But sometimes we need it badly. So there is a way around to do this easily.

You should note that scopes are initialized after the page is fully loaded, so calling methods from outside of scope should always be done after the page is loaded. Else you will not get to the scope at all. Below is a small code snippet to how you can achieve this easily:

var targetID = document.getElementById("AngularController");
angular.element(targetID).scope().init("Outside Controller");

Where "init" is function named in your controller as below:

var app = angular.module("myApp", []);
app.controller("AngularController", function($scope, $window) {
    $scope.init = function(res) {
        console.log("INIT INVOKED=" + res);
    };

    $scope.init("Controller Itself");
});








You can download full example from the link.


Friday, February 15, 2013

cakephp cpanel api component and controller

Update: added WHM accessKey support
The cPanel API component requires cURL to connect to the cPanel server.
The cURL part can be replaced with CakePHP's internal HttpSocket class, but at the time of this writing there is no SSL support in the HttpSocket class, so that cURL is used in this example.

Component Class:

<?php  /**
 * The cPanel API component provides easy controller integration with cPanel API calls.
 * Requires cURL support. 
 * 
 * @author Hendrik Daldrup <hendrik@jinarigo.ca>
 */
class CpanelApiComponent extends Object {

    var 
$disableStartup true;
    
    
/**
     * WHM domain name
     *
     * @var string
     * @access private
     */
    
var $__domain '';
    
    
/**
     * WHM port
     * default http port 2086
     * default https port 2087
     * 
     * @var integer
     * @access private
     */
    
var $__port 2086;
    
    
/**
     * WHM username
     *
     * @var string
     * @access private
     */
    
var $__user '';
    
    
/**
     * WHM password
     *
     * @var string
     * @access private
     */
    
var $__pass '';
    
    
/**
     * WHM accessKey
     *
     * @var string
     * @access private
     */
    
var $__accessKey '';
    
    
/**
     * Connect via https
     *
     * @var boolean
     * @access private
     */
    
var $__ssl false;
    
    
/**
     * cPanel URL string
     *
     * @var string
     * @access private
     */
    
var $__url '';
    
    
/**
     * Generate the cPanel URL, returns true on success.
     *
     * @param array $params Must include domain, user and pass. Port and SSL optional.
     * @return boolean
     */
    
function init($params = array()) {
        
        if (isset(
$params['domain']) && $params['domain'] != ''$this->__domain $params['domain'];
        else return 
false;
        
        if (isset(
$params['user']) && $params['user'] != ''$this->__user $params['user'];
        else return 
false;
        
        if (isset(
$params['pass']) && $params['pass'] != '') { 
            
$this->__pass $params['pass'];
        } else if (isset(
$params['accessKey']) && $params['accessKey'] != '') { 
            
$this->__accessKey $params['accessKey'];
        } else { 
            return 
false;
        }
        
        if (isset(
$params['port']) && $params['port'] != ''$this->__port $params['port'];
        if (isset(
$params['ssl']) && $params['ssl'] != ''$this->__ssl $params['ssl'];

        if (
$this->__ssl) {
            
$this->__url 'https';
        } else {
            
$this->__url 'http';
        }
        
$this->__url .= '://'.$this->__domain.':'.$this->__port;
        
        return 
true;
    }
    
    
/**
     * Sends a cPanel API query and returns the result 
     *
     * @param string $query cPanel API query to send, e.g.: '/xml-api/applist'
     * @return string
     */
    
function query($query null) {
        if (
$query) {
            
$ch curl_init();
            
curl_setopt($chCURLOPT_URL$this->__url.$query);
            
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
            
curl_setopt($chCURLOPT_RETURNTRANSFER1);
            if (isset(
$this->__accessKey) && $this->__accessKey != '') {
                
curl_setopt($chCURLOPT_HEADER0);
                
$customHeader[0] = "Authorization: WHM ".$this->__user.':'.$this->__accessKey;
                
curl_setopt($ch,CURLOPT_HTTPHEADER$customHeader);
            } else {
                  
curl_setopt($chCURLOPT_USERPWD$this->__user.':'.$this->__pass);
                
curl_setopt($chCURLOPT_HTTPAUTHCURLAUTH_ANY);
            }
            
$result curl_exec($ch);
            
curl_close($ch);

            return 
$result;
        }
        return 
false;
    }
    
}    
?>

Controller Class:

<?php  class CpanelController extends AppController  {
    var 
$name 'Cpanel';
    var 
$components = array('CpanelApi');
    
    function 
cpanelTest() {
        if (
$this->CpanelApi->init(array(
            
'domain' => 'WhmDomainName',
            
'user' => 'WhmUsername',
            
'pass' => 'WhmPassword',
            
//'accessKey' => 'WhmAccessKey',
            
'port' => 2086,
            
'ssl' => false))) 
        {
            
$cpanelData $this->CpanelApi->query('/xml-api/applist');
            
$this->set('cpanelData'$cpanelData);
        } else {
            
$this->Session->setFlash('Error in CpanelApiComponent init()');
        }
    }
}
?> 

Replace the WhmDomainName, WhmUsername and WhmPassword with the correct values of your WHM account.
The port and ssl values are optional, just make sure to change both, if you wish to use SSL support.
You can use the result to extract the data as needed. In this case it simply sends the result to the view.

It's also possible to use your WHM access key now. To do so, simply uncomment the 'accessKey' line in above controller example and remove the 'pass' line. Make sure to enter your access key as a single line, without any additional characters.

I hope this is usefull to someone and I will add a HttpSocket example, once SSL support is available.

http://bakery.cakephp.org/articles/Duncan/2008/07/15/cpanel-api-component