"'this.byId' is not a Function" error in console - dependency-injection

I have a script file that I would like to load into a Main.controller.js
myScript.js
sap.ui.define([], function () {
return {
/////
testFunc : function(){
var test = this.byId("someId");
console.log(test);
};
});
The myScript.js file is successfully read in the main controller when I load it in as a dependency (see below), but I get an error in the myScript.js :
"'this.byId' is Not a Function" (console.log)
Inside the main controller, "this.byId()" works because the 'this' keyword points to the xml view associated with the main controller (main.view.xml). How can I have a dependency like 'myScript.js' point to the same xml view as the controller that loads it?
main controller
sap.ui.define([
'jquery.sap.global',
'sap/ui/core/mvc/Controller',
'sap/ui/model/json/JSONModel',
'sap/ui/model/Filter',
'sap/ui/model/FilterOperator',
'pricingTool/controller/myScript'
],
function (jQuery, Controller, JSONModel, Filter, FilterOperator, myScript) {
"use strict";
var mainController = Controller.extend("pricingTool.controller.Main", {
myScript.testFunc();
...
});
return mainController;
});
main.view.xml
<mvc:View
controllerName="pricingTool.controller.Main"
xmlns:l="sap.ui.layout"
xmlns:core="sap.ui.core"
xmlns:f="sap.ui.layout.form"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m">
...
</mvc:View>

You need to change the context passed to the script function. You can do this with following code:
myScript.testFunc.apply(this);
Let me know if this resolved your issue.

Related

Calling controller method with a get type not working in ASP.NET MVC

I have a java script function that calling a controller method using Ajax, this call should get me the user profile page, I have a controller for this purpose. When I run the program and fire the java script function it's trigger the controller and every thing is good but when the debugging has ended no changes happens and the view doesn't present in the screen.
I tracked the call and every thing is working fine, passing parameter and reaching the method in the controller.
Note: the view which has the JS call related to a different controller.
View contain java script call:
<td onclick="ViewProfile('#item.CustomerId')"></td>
Java script file
function ViewProfile(id) {
console.log("sucsses");
$.ajax({
type:"GET",
url: "/ViewUserProfile/Index",
data: { "userId": id }
});
};
Controller: ViewUserProfileController
public ActionResult Index(string userId)
{
var ProfileInformation = new UserProfileVM
{
//some logic here
};
return View(ProfileInformation);
}
You are fetching ViewUserProfile in $.ajax but you are not using .done(function() { }) to process the result you receive from that call.
In your case I would simply suggest to use window.location.href in ViewUserProfile() as below.
function ViewProfile(id) {
window.location.href = "/ViewUserProfile/Index?userId=" + id;
}

Binding click event with css class in angular 7

Is there any way to bind click event with class name in angular 7 like we used to with jquery?
In jquery I was able to do this
$('.my-class-name').on('click',function(){});
Is there something similar standard way in angular 7?
You can directly add the click event to the HTML tag which has the required class
In your case:
****** Method 1 ******
lets say you are writing the above className on a button, then
<button class="my-class-name" (click)="yourFunction($event)">
Your button
</button>
If you want to add it from the TS File only, then you can use the following method:
*** Method 2 ******
**STEP 1:**
// Create a view child template reference
#viewChild('someName', {static: false})
private someNameVC: ElementRef
**STEP 2:**
// Add this 'someName' to the HTML Element in .html FIle
<button class="my-class-name" #someName>
Your button
</button>
**STEP 3:**
// In your component.ts file, whenever you want to add the event listener, create a function and do the following :
yourMainFunction() {
if (someCondition) {
this.addEventListenerToButtonMethod();
......rest of the code
}
}
addEventListenerToButtonMethod() {
const parentElement: HTMLElement =
this.someNameVC.nativeElement.parentNode as HTMLElement;
// Here you can add your event listener
parentElement.addEventListener('click', function() {});
}

JQuery function function wont work when page is returned via Partial view

I have this jquery function placed in my .js file.... As long as my page is loaded this works... but when i changed it to return as a partial view.... this alert wont work anymore... How is it gonna be working again ?
$(document).ready(function () {
var msg = '#ViewBag.Message';
if (msg == '1')
alert("New Time Shift has been saved.");
});
In my controller action...
if (Request.IsAjaxRequest())
return PartialView("_RecordList", userRecord); //alert wont work here...
return View(userRecord); //this will return the whole view thus the alert works here
The document ready function will not be executed from ajax requests.
You could extract the javascript code to a separated function part of the whole view. You can also create a callback function to be executed when the partial request succeeds, that will also call it:
$(document).ready(function () {
var msg = '#ViewBag.Message';
initFunction(msg);
});
function initFunction(msg){
if (msg == '1')
alert("New Time Shift has been saved.");
}
function partialRequestSuccess(data){
//store the message somewhere in the partial view, like a hidden div and get it using jquery
var msg = ...
initFunction(msg);
}
Then you could set the complete callback of the ajax request to call the success callback we have just created. If you are using the MVC ajax helpers, there is a Success parameter that you can set like:
#using(Ajax.BeginForm(new AjaxOptions{ OnSuccess = "partialRequestSuccess" }))
I have this jquery function placed in my .js file....
var msg = '#ViewBag.Message';
This is server code, that works only in *.cshtml files, this is minimum one problem.

Pass Javascript callback function to partial view MVC

I'm wondering if this is the right way of passing a JavaScript callback function to a partial view. So depending on the view I'm on the partial view may do different things. So I pass in a JavaScript call back function to achieve that.
Here is a generic function to call my partial view and where I pass in the JavaScript call back function.
function showAjaxMessage(targetDiv, ajaxMessage) {
var ajaxLoader = "<img src='Content/loader.gif' alt=''>";
$(targetDiv).html("<p>" + ajaxLoader + " " + ajaxMessage+"</p>");
}
function getPartialView(actionUrl, targetDiv, ajaxMessage, cbFunc) {
showAjaxMessage(targetDiv, ajaxMessage);
$.get(actionUrl, { callback: eval(cbFunc).toString()}, function(result) {
$(targetDiv).html(result);
});
}
Here is an example of me calling it:
getPartialView("Home/OpenLogin", "#divLogon", "Loading...", function() { alert('This is the call back function!'); test(); });
Here is the controller where I get the callback function and save it to a model. Then I pass it back to the partial view.
// returns a login dialog which will be injected
// into a placeholder div on the client
public ActionResult OpenLogin(string callback)
{
var baseModel = new BaseModel();
baseModel.cbFunc = callback;
return PartialView("LoginDialog", baseModel);
}
Here is an example of my partial view. Where you can see I get the call back function and set in the init function.
#model MvcApplication8.Models.BaseModel
function init(cb){
if(cb!=undefined){
cb();
}
else{
alert("undefined");
}
}
function test(){
alert("Testing my call back");
}
$(function () {
init(#Html.Raw(#Model.cbFunc));
});
The solution above works, but the main question that comes to mind is this the right way of doing it? Passing the call back function from the controller to the partial view sounds wrong, but how else would you do it? Any ideas?
Based on your example, I do not understand why would pass the callback function to a partial view. The partial view is rendered inside a div on the same page. Why not just declare the function on the page so that it's available to the rendered partial view?

Unable to move from JQuery.live() to JQuery.on()

I am loading some html via $.get() into a Jquery-dialog-popup.
Upon clicking a link in the newly inserted html some function should be triggered.
This works with live() but NOT with on().
This works:
$(".remove").live("click", function () {
// enter ok
}
This does not:
$("div").on("click", ".remove", function () {
// or $("#delete").on("click", ".remove", function () {
// or $(".remove").on("click", function () {
// never enters...
});
html:
<div id="delete">
<a class="remove" href="#">link</a>
</div>
The on()-function works in case I am calling it directly from my main-template without loading the content into a dialog-window first via $.get.
To pre-bind events for dynamic content, they have to be bound to a pre-existing element.
So, if the <div id="delete"> is part of the dynamic content, then you shouldn't use it to bind the event. You can, however, bind to the container that the dynamic content is loaded into.
So, if the resulting HTML is:
<div id="contents">
<!-- start template -->
<div id="delete">
<a class="remove" href="#">link</a>
</div>
<!-- end template -->
</div>
Then, your JavaScript can be:
$('#contents').on('click', 'div a.remove', function () {
// ...
});
.live() uses document for this -- an element that exists until reload or redirect -- making the following lines equivalent:
$("a.remove").live("click", function () { /* ... */ });
$(document).on("click", "a.remove", function () { /* ... */ });
I can't see the whole code but I would bet that you're not putting the
$("div").on("click", ".remove", function () {
// or $("#delete").on("click", ".remove", function () {
// or $(".remove").on("click", function () {
// never enters...
}
part ONCE the new code has been inserted into the DOM.
You need to attach the event listeners to the new elements created. Live works because it works for existing and future elements like that.
EDIT:
If you want the click handler to work for an element that gets loaded dynamically, then you need to set the event handler on a parent object (that does not get loaded dynamically) and give it a selector that matches your dynamic object like this:
$('#parent').on("click", ".remove", function() {});

Resources