Skip to Content

Accessing to function in View Content from Controller SAPUI5

Hi,

Can I accessing to function in View Content from Controller ?

From controller I want to call openDialog()

createContent : function(oController) {
 
     function openDialog() {
           alert("Ok!");
     }

}

Thank you

Add a comment
10|10000 characters needed characters exceeded

Assigned Tags

Related questions

2 Answers

  • Best Answer
    Posted on Dec 16, 2014 at 10:55 AM

    Hi,

    This is definitely not what you want to do to follow best practices for MVC concepts as Robin stated. The open dialog function should be placed in the controller and then the view calls if from there. I feel there is more to your question though.

    It is also important to understand how you could do this, since there could be different situations that need something similar and for general understanding of javascript.

    This is not possible how you have written your sample code. The function "openDialog" is only visible in the scope of the createContent function and cannot be called from outside. You could expose it in numerous ways, one being:

    createContent : function(oController) {  
       
      // Creates a new function on the "this" object that can be called by anyone who has a reference to "this"
    // Note that this function only exists after the "createContent" method is called so it is not safe to assume it exists all the time
         this.openDialog = function() {  
               alert("Ok!");  
         }; 
    }
    
    // In the controller
    var view = this.getView();
    if (typeof view.openDialog === "function") {
          this.getView().openDialog();
    }
    

    It would be best that the function be in the controller, or if it is not just for one controller, can be placed in a utility or dedicated external object?

    Oli

    Add a comment
    10|10000 characters needed characters exceeded

  • Posted on Dec 16, 2014 at 09:03 AM

    I don't think you can, but more importantly, you shouldn't either.

    According to true MVC principles, a view should not contain any logic, so a view can (should) only access functions from a controller.

    To solve your issue, simply move the function from the view to the controller and call it from there

    Add a comment
    10|10000 characters needed characters exceeded

Before answering

You should only submit an answer when you are proposing a solution to the poster's problem. If you want the poster to clarify the question or provide more information, please leave a comment instead, requesting additional details. When answering, please include specifics, such as step-by-step instructions, context for the solution, and links to useful resources. Also, please make sure that you answer complies with our Rules of Engagement.
You must be Logged in to submit an answer.

Up to 10 attachments (including images) can be used with a maximum of 1.0 MB each and 10.5 MB total.