Adam Jakś
Adam Jakś

Reputation: 73

How to call function assigned to variable with parameter

I have a structure like this:

//function declaration
someFunc() = {
 // ...
}

//assign function to variable
let f = someFunc();

//call
f();

I want to pass arguments to someFunc() with calling this function by variable, like:

f(arg); 

but f is not a variable then. How to process the parameter in fucntion by this way?

Edit: In the question above, I thought about calling a function by variable. Something like:

{{ f }}

and that f is assigned to function which returns some value.

Why I do that is because I need to initialize function in ngOnInit lifecycle (my goal is to call function just one time).

My view and ts code below:

TS:

import {Component, OnInit, Input} from '@angular/core';
import {Router} from "@angular/router";
import {PostsService} from "../../services/posts.service";
import {AuthService} from "../../services/auth.service";
import {ConfirmationModalService} from "../../services/confirmation-modal.service";
import {LoaderService} from "../../services/loader.service";
import {ToastService} from "../../services/toast.service";

declare var M: any;

@Component({
    selector: 'app-posts',
    templateUrl: './posts.component.html',
    styleUrls: ['./posts.component.scss']
})
export class PostsComponent implements OnInit {
    avatar: string;
    loggedUser: any;
    modalId: any;
    editModal: any;
    editModalInstance: any;
    content: string;
    contentEdited: string;
    orderSelect: any;
    orderSelectInstance: any;
    showButton: boolean;
    getAvatar: any;

    constructor(private postsService: PostsService, private authService: AuthService,
                private router: Router, private confirmationModalService: ConfirmationModalService,
                private loaderService: LoaderService, private toastService: ToastService) {
    }

    ngOnInit() {

        this.showButton = true;

        this.editModal = document.querySelector('#edit-modal');
        this.editModalInstance = M.Modal.init(this.editModal);

        this.orderSelect = document.querySelectorAll('#post-order-select');
        this.orderSelectInstance = M.FormSelect.init(this.orderSelect);

        this.orderSelect = 'post_date';

        this.loggedUser = localStorage.getItem('user') ?
            JSON.parse(localStorage.getItem('user')).id : '';

        this.loaderService.isLoading = true;

        this.postsService.getPosts().subscribe(response => {
            this.postsService.getPostHandling(response);
            this.loaderService.hideLoader();
        }, err => {
            this.toastService.error(err);
            this.loaderService.hideLoader();
            return false;
        });

        this.getAvatar = this.getCreatorAvatar(123);
    }

    loadMore() {
        this.loaderService.isLoadingSmall = true;
        if (this.orderSelect === 'post_date') {
            this.postsService.getPosts(true).subscribe(response => {
                if (this.postsService.postIndex > response.posts.length) {
                    this.showButton = false;
                }
                this.postsService.getPostHandling(response);
                this.loaderService.hideLoaderSmall();
            }, err => {
                this.toastService.error(err);
                this.loaderService.hideLoaderSmall();
                return false;
            });
        } else if (this.orderSelect === 'rate') {
            this.postsService.getPostsOrdered(true).subscribe(response => {
                if (this.postsService.postIndex > response.posts.length) {
                    this.showButton = false;
                }
                this.postsService.getPostHandling(response);
                this.loaderService.hideLoaderSmall();
            }, err => {
                this.toastService.error(err);
                this.loaderService.hideLoaderSmall();
                return false;
            });
        }
    }

    order(orderSelect) {
        this.loaderService.isLoading = true;
        if (orderSelect === 'post_date') {
            this.postsService.getPosts().subscribe(response => {
                this.postsService.getPostHandling(response);
            }, err => {
                this.toastService.error(err);
                return false;
            });
        } else {
            this.loaderService.isLoading = true;
            this.postsService.getPostsOrdered().subscribe(response => {
                this.postsService.getPostHandling(response);
            }, err => {
                this.toastService.error(err);
                return false;
            });
        }
        this.loaderService.hideLoader();
    }

    onEditModalSubmit() {
        this.editModalInstance.close();
        this.postsService.editPost(this.modalId, this.contentEdited).subscribe(data => {

            if (data.success) {
                this.loaderService.isLoading = true;
                this.postsService.getPosts().subscribe(response => {
                    this.postsService.getPostHandling(response);
                }, err => {
                    this.toastService.error(err);
                    return false;
                });
                this.loaderService.hideLoader();
                this.toastService.success(data.msg);
            } else {
                console.log('some error');
            }
        });
    }

    openEditModal(id, content) {
        this.modalId = id;
        this.editModal.querySelector('#textarea-edit').value = content;
        this.editModalInstance.open();
    }

    deletePost(id) {
        this.confirmationModalService.content = 'Are you sure you want to delete this post?';
        this.confirmationModalService.cta = 'Delete';
        this.confirmationModalService.proceed = () => {
            this.postsService.deletePost(id).subscribe(data => {
                if (data.success) {
                    this.toastService.success(data.msg);
                    this.loaderService.isLoading = true;
                    this.postsService.getPosts().subscribe(response => {
                        this.postsService.getPostHandling(response);
                        this.loaderService.hideLoader();
                    }, err => {
                        this.toastService.error(err);
                        return false;
                    });
                } else {
                    this.toastService.error(data.msg);
                }

            });
            this.authService.decreasePostAmount(JSON.parse(localStorage.getItem('user')).id)
                .subscribe(() => {
                });
            this.confirmationModalService.modalInstance.close();
        };
        this.confirmationModalService.modalInstance.open();
    }

    ratePost(id, creator_id) {
        this.postsService.ratePost(id, creator_id).subscribe(() => {
            if (this.orderSelect === 'post_date') {
                this.postsService.getPosts().subscribe(response => {
                    this.postsService.getPostHandling(response);
                }, err => {
                    this.toastService.error(err);
                    return false;
                });
            } else if (this.orderSelect === 'rate') {
                this.loaderService.isLoading = true;
                this.postsService.getPostsOrdered().subscribe(response => {
                    this.postsService.getPostHandling(response);
                    this.loaderService.hideLoader();
                }, err => {
                    this.toastService.error(err);
                    this.loaderService.hideLoader();
                    return false;
                });
            }
        });
    }

    revertRate(id, loggedUser_id) {
        this.postsService.revertRatePost(id, loggedUser_id).subscribe(() => {
            if (this.orderSelect === 'post_date') {
                this.postsService.getPosts().subscribe(response => {
                    this.postsService.getPostHandling(response);
                }, err => {
                    this.toastService.error(err);
                    return false;
                });
            } else if (this.orderSelect === 'rate') {
                this.loaderService.isLoading = true;
                this.postsService.getPostsOrdered().subscribe(response => {
                    this.postsService.getPostHandling(response);
                    this.loaderService.hideLoader();
                }, err => {
                    this.toastService.error(err);
                    this.loaderService.hideLoader();
                    return false;
                });
            }
        });
    }

    isLiked(users_liked) {
        return users_liked.indexOf(this.loggedUser) > -1;
    }

    getCreatorId(post) {
        return post.creator[0]['id'];
    }

    getCreatorName(post) {
        return post.creator[0]['name'];
    }

    getCreatorAvatar(id) {
        this.authService.getAvatar(id).subscribe(data => {
            this.avatar = data.avatar;
        });
    }
}

HTML:

<div class="row">
    <div class="input-field col s3">
        <select id="post-order-select"
                [(ngModel)]="orderSelect" name="orderSelect" (change)="order(orderSelect)">
            <option value="post_date">Recent posts</option>
            <option value="rate">Most rated</option>
        </select>
        <label>Order by</label>
    </div>
</div>
<div id="post-list" class="post-list">
    <ng-container *ngIf="!loaderService.isLoading">
        <div *ngFor="let post of postsService.posts" class="card-panel first"
             [ngClass]="{'own-post' : authService.loggedIn() && getCreatorId(post) === loggedUser}">
            <div class="post-details">
                <div class="post-header">
                    <div class="author-avatar"
                         [ngStyle]="{ 'background-image' : 'url(' + getAvatar + ')'}">
                    </div>
                    <div class="post-info">
                        <div class="author-fullname grey-text text-darken-3">{{ getCreatorName(post) }}</div>
                        <div class="post-date deep-orange-text">{{ post.post_date | timeago }}</div>
                    </div>
                </div>
                <div class="teaser grey-text text-darken-1" [innerHTML]="post.content"></div>
                <div class="valign-wrapper rate">
                    <ng-container *ngIf="authService.loggedIn() && post.creator.id !== loggedUser">
                        <i *ngIf="!isLiked(post.users_liked)"
                           class="material-icons tiny deep-orange-text text-lighten-4"
                           (click)="ratePost(post._id, loggedUser)">thumb_up</i>
                        <i *ngIf="isLiked(post.users_liked)" class="material-icons tiny deep-orange-text"
                           (click)="revertRate(post._id, loggedUser)">thumb_up</i>
                    </ng-container>
                    <ng-container *ngIf="authService.loggedIn() && post.creator.id === loggedUser">
                        <i class="material-icons tiny deep-orange-text text-lighten-4 own">
                            thumb_up
                        </i>
                    </ng-container>
                    <ng-container *ngIf="!authService.loggedIn()">
                        <i class="material-icons tiny deep-orange-text text-lighten-4 own">
                            thumb_up
                        </i>
                    </ng-container>
                    <span class="grey-text text-darken-3">{{ post.rate }}</span>
                </div>
            </div>
            <ng-container *ngIf="authService.loggedIn() && post.creator.id === loggedUser">
                <a class="btn-floating btn-medium deep-orange darken-3 right"
                   (click)="deletePost(post._id)">
                    <i class="material-icons">delete</i>
                </a>
                <a class="btn-floating btn-medium deep-orange right"
                   (click)="openEditModal(post._id, post.content)">
                    <i class="material-icons">create</i>
                </a>
            </ng-container>
        </div>
        <div *ngIf="loaderService.isLoadingSmall"
             class="row">
            <div class="col s12 center-align">
                <div class="preloader-wrapper small active">
                    <div class="spinner-layer">
                        <div class="circle-clipper left">
                            <div class="circle"></div>
                        </div>
                        <div class="gap-patch">
                            <div class="circle"></div>
                        </div>
                        <div class="circle-clipper right">
                            <div class="circle"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div *ngIf="!loaderService.isLoadingSmall && showButton === true" class="row">
            <div class="col s12 center-align">
                <button (click)="loadMore()" class="btn deep-orange">Load more</button>
            </div>
        </div>
    </ng-container>
</div>

<div *ngIf="loaderService.isLoading" class="row">
    <div class="col s12 center-align">
        <div class="preloader-wrapper big active">
            <div class="spinner-layer">
                <div class="circle-clipper left">
                    <div class="circle"></div>
                </div>
                <div class="gap-patch">
                    <div class="circle"></div>
                </div>
                <div class="circle-clipper right">
                    <div class="circle"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="edit-modal" class="modal">
    <div class="modal-content">
        <form (submit)="onEditModalSubmit()">
            <div class="row">
                <div class="col s12">
                    <div class="input-field deep-orange-text">
                    <textarea id="textarea-edit" [(ngModel)]="contentEdited" name="contentEdited"
                              class="materialize-textarea"></textarea>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col s12">
                    <button type="submit" class="btn grey darken-4 right">Confirm editing</button>
                    <a href="#" (click)="editModalInstance.close()" class="btn grey darken-1 right">Cancel</a>
                </div>
            </div>
        </form>
    </div>
</div>

Upvotes: 0

Views: 386

Answers (4)

Pardeep Jain
Pardeep Jain

Reputation: 86800

You need to assign your function without () to variable like below -

const myVar = someFunc;

If you assign function into some variable without parenthsis () it will assign ref. of the function which is needed in your use case.

Upvotes: 0

Moumen Soliman
Moumen Soliman

Reputation: 1674

Add f as a reference so you can do that

let f = someFunc

or Add it a function

let f = someFunc();

or use it as a constant

const f = someFunc(); // f = someFunc

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386858

You need to assign the function without calling the function.

let f = someFunc;

Upvotes: 1

Pointy
Pointy

Reputation: 413996

The statement

let f = someFunc();

assigns the result of calling someFunc() to f. If you want f to be a reference to the function itself, you need

let f = someFunc;

A reference to a function followed by () or a parenthesized list of parameters is a function call.

Upvotes: 4

Related Questions