Durandal dialog Call back Function - durandal-2.0

In my view model I have a grid, if user click on Edit button on the row it will popup a dialog with row values, if user click on Edit button will close the dialog then I need to reload the grid. My model look like below, I my case
I am not able to call load function after dialog call back (** getting Error - self is undefined**). it is possible to pass this to dialog?
var ctor = function () {
var self = this;
self.load = function () {
Load grid Functions
}
self.editRow = function (row) {
dialog.show(new editWindow(), row).then(function (response) {
if (response == null) {
return;
}
self.load();
});
}
Return ctor;

got answer by adding self with call back
var ctor = function () {
var self = this;
self.load = function () {
Load grid Functions
}
self.editRow = function (row) {
dialog.show(new editWindow(), row).then(function (response) {
if (response == null) {
return;
}
self.load();
},self);
}
Return ctor;

Related

Preserving DOM after ajax call

I am new to Angular, and with many days of frustration, I have found that after Ajax call the DOM is remodelled, that cleared things for me but as I am pretty new to Angular, I cannot figure out how to keep it together. Right now when my Ajax call happens, the code breaks everything, I tried the following code after my Ajax request but now my carousel has disappeared.
this.currentIndex = 0;
this.slickConfig = {
event: {
afterChange: function (event, slick, currentSlide, nextSlide) {
this.currentIndex = currentSlide; // save current index each time
}
init: function (event, slick) {
slick.slickGoTo($scope.currentIndex); // slide to correct index when init
}
}
};
While init gives a red underline.
My ajax call is like following
this.httpClientService.postAjaxForm(link, postData)
.subscribe(response => {
if (response["x"] != undefined && response["x"] != null) {
this.x= response["x"];
this.currentIndex = 0;
this.slickConfig = {
event: {
afterChange: function (event, slick, currentSlide, nextSlide) {
this.currentIndex = currentSlide; // save current index each time
}
init: function (event, slick) {
slick.slickGoTo($scope.currentIndex); // slide to correct index when init
}
}
};
}
Why the above call won't let my carousel work normally and when ajax call is made why the page is broken?

Kendo Grid always focus on first cell of Top Row

I have checkbox in Kendo grid. Once i click on Checkbox it always focus the top cell in Kendo Grid. Below is code for Kendo grid that I am binding to checkbox value on checkbox click event in Kendo Grid
$("#contactgrid").on('click', '.chkbx', function () {
var checked = $(this).is(':checked');
var grid = $('#contactgrid').data().kendoGrid;
var rowIdx = $("tr", grid.tbody).index(row);
var colIdx = $("td", row).index(this);
// grid.tbody.find("tr").eq(rowIndex).foucs(); This doesn't work
var dataItem = grid.dataItem($(this).closest('tr'));
dataItem.set('IsSelected', checked);
});
I can get the row index and cell Index in click event but I was not able to figure out to focus the specific cell.
Thanks!
When you want to edit Grid with checkbox then I would suggest you to use the approach from this code library. No matter it uses the MVC extensions open Views/Home/Index.cshtml and see how the template is defined and the javascript used after initializing the Grid.
Here it is
Column template:
columns.Template(#<text></text>).ClientTemplate("<input type='checkbox' #= IsAdmin ? checked='checked':'' # class='chkbx' />")
.HeaderTemplate("<input type='checkbox' id='masterCheckBox' onclick='checkAll(this)'/>").Width(200);
<script type="text/javascript">
$(function () {
$('#persons').on('click', '.chkbx', function () {
var checked = $(this).is(':checked');
var grid = $('#persons').data().kendoGrid;
var dataItem = grid.dataItem($(this).closest('tr'));
dataItem.set('IsAdmin', checked);
})
})
function checkAll(ele) {
var state = $(ele).is(':checked');
var grid = $('#persons').data().kendoGrid;
$.each(grid.dataSource.view(), function () {
if (this['IsAdmin'] != state)
this.dirty=true;
this['IsAdmin'] = state;
});
grid.refresh();
}
</script>
I struggled with this. I essential refocused the cell as shown below. There's plenty of room for improvement in the Kendo grid client-side API. Hopefully my helper methods below will help people out.
var $row = getRowForDataItem(this);
var $current = getCurrentCell($row);
var currentCellIndex = $row.find(">td").index($current);
this.set('PriceFromDateTime', resultFromDate);
$row = getRowForDataItem(this);
var grid = getContainingGrid($row);
//select the previously selected cell by it's index(offset) within the td tags
if (currentCellIndex >= 0) {
grid.current($row.find(">td").eq(currentCellIndex));
}
//Kendo grid helpers
function getColumn(grid, columnName) {
return $.grep(grid.columns, function (item) {
return item.field === columnName;
})[0];
}
function getRowForDataItem(dataItem) {
return $("tr[data-uid='" + dataItem.uid + "']");
}
function getCurrentCell($elem) {
return getContainingGrid($elem).current();
}
function getContainingDataItem($elem) {
return getDataItemForRow(getContainingRow($elem));
}
function getContainingCell($elem) {
return $elem.closest("td[role='gridcell']");
}
function getContainingRow($elem) {
return $elem.closest("tr[role='row']");
}
function getContainingGrid($elem) {
return $elem.closest("div[data-role='grid']").data("kendoGrid");
}
function getGridForDataItem(dataItem) {
return getContainingGrid(getRowForDataItem(dataItem));
}
function getDataItemForRow($row, $grid) {
if (!$grid) $grid = getContainingGrid($row);
return $grid.dataItem($row);
}
function getMasterRow($element) {
return $element.closest("tr.k-detail-row").prev();
}
function getChildGridForDataItem(dataItem) {
return getRowForDataItem(dataItem).next().find("div.k-grid").data("kendoGrid");
}
function getMasterRowDataItem($element) {
var $row = getMasterRow($element);
return getDataItemForRow($row);
}

Update knockout viewmodel when uploading documents via ajax

I'm trying to use knockout for a view where I'm uploading documents and showing a list. For this I'm using jquery.form.js in order to upload them using ajax. I've changed that to use knockout and my viewmodel looks like this
var ViewModel = function (groups) {
var self = this;
self.groups = ko.observableArray(ko.utils.arrayMap(groups, function (group) {
return {
planName: ko.observable(group.Key),
documentList: ko.observableArray(ko.utils.arrayMap(group.Values, function (value) {
return {
document: ko.observable(new Document(value))
};
}))
};
}));
var options = {
dataType: 'json',
success: submissionSuccess
};
self.add = function () {
$('#addForm').ajaxSubmit(options);
return false;
};
function submissionSuccess(result) {
alert('success');
}
};
Having one Document function for doing the mapping. I'm stuck when receiving the Json data from the controller. The result is correct, a list of objects in the same format I'm receiving on first load but I don't know how to "refresh" the viewmodel to use this new list.
Don't know if using the ko mapping plugin would make it easier as I have never used it and don't even know if it's applicable for this.
The controller method, in case is relevant, is this (if something else neede let me know althoug won't have access to the code in the next hours)
[HttpPost]
public ActionResult AddDocument(AddDocumentViewModel viewModel)
{
var partyId = Utils.GetSessionPartyId();
if (viewModel.File.ContentLength > Utils.GetKBMaxFileSize * 1024)
ModelState.AddModelError("File", String.Format("The file exceeds the limit of {0} KB", Utils.GetKBMaxFileSize));
if (ModelState.IsValid)
{
_documentsManager.AddDocument(viewModel, partyId);
if (Request.IsAjaxRequest())
{
var vm = _displayBuilder.Build(partyId);
return Json(vm.Documents);
}
return RedirectToAction("Index");
}
var newViewModel = _createBuilder.Rebuild(viewModel, partyId);
return PartialView("_AddDocument", newViewModel);
}
Thanks
EDIT: I came up with this code which seems to work (this function is inside the ViewModel one
function submissionSuccess(result) {
self.groups(ko.utils.arrayMap(result, function (group) {
return {
planName: ko.observable(group.Key),
documentList: ko.utils.arrayMap(group.Values, function (value) {
return {
document: new Document(value)
};
})
};
}));
};
Are you sure the documentList and document need to be observables themselves ?
To update the list you can push to it as you'd do on a regular array.
You could try something like this:
function submissionSuccess(result) {
self.groups.removeAll();
$.each(result, function(index, value) {
var documentList = [];
$.each(value.Values, function(index, value) {
documentList.push(new Document(value));
});
var group = {
planName:value.Key,
documentList: documentList
};
self.groups.push(group);
});
};

WooCommerce plugin , add variation to cart via Ajax

Im looking for a solution to add a product variation via Ajax.
As i found out all the WooCommerce basic functions allow adding a product to the cart only if it is not a variation item.
im using <?php echo woocommerce_template_loop_add_to_cart() ?> to display the add to cart button but this button is a regular submit button.
how can i make a variable item use the Ajax add to cart ?
I created and AJAX add to cart for variable products like this:
Sorry about the delay, here is the expanded answer:
I included a new js file called added-to-cart.js and the file contains the following code. There is some extra code for handling a popup and also increasing the cart counter which you might want to remove.
/* Begin */
jQuery(function($) {
/* event for closing the popup */
$("div.close").hover(
function() {
$('span.ecs_tooltip').show();
},
function () {
$('span.ecs_tooltip').hide();
}
);
$("div.close").click(function() {
disablePopup(); // function close pop up
})
$("a.close").click(function() {
disablePopup(); // function close pop up
});
$(this).keyup(function(event) {
if (event.which == 27) { // 27 is 'Ecs' in the keyboard
disablePopup(); // function close pop up
}
});
$("div#backgroundPopup").click(function() {
disablePopup(); // function close pop up
});
$('a.livebox').click(function() {
//alert('Hello World!');
return true;
});
setAjaxButtons(); // add to cart button ajax
function loading() {
$("div.loader").show();
}
function closeloading() {
$("div.loader").fadeOut('normal');
}
// AJAX buy button for variable products
function setAjaxButtons() {
$('.single_add_to_cart_button').click(function(e) {
var target = e.target;
loading(); // loading
e.preventDefault();
var dataset = $(e.target).closest('form');
var product_id = $(e.target).closest('form').find("input[name*='product_id']");
values = dataset.serialize();
$.ajax({
type: 'POST',
url: '?add-to-cart='+product_id.val(),
data: values,
success: function(response, textStatus, jqXHR){
loadPopup(target); // function show popup
updateCartCounter();
},
});
return false;
});
}
function updateCartCounter() {
var counter = $('.widget_shopping_cart_content').text().replace(/\s/g, '');
if (counter == '') {
$('.widget_shopping_cart_content').text("1");
}
else {
$('.widget_shopping_cart_content').text(++counter);
}
}
var popupStatus = 0; // set value
function loadPopup(target) {
var currentPopup = $(target).parents(".single_variation_wrap").find("#toPopup");
var currentBgPopup = $(target).parents(".single_variation_wrap").find("#backgroundPopup");
if(popupStatus == 0) { // if value is 0, show popup
closeloading(); // fadeout loading
currentPopup.fadeIn(0500); // fadein popup div
currentBgPopup.css("opacity", "0.7"); // css opacity, supports IE7, IE8
currentBgPopup.fadeIn(0001);
popupStatus = 1; // and set value to 1
}
}
function disablePopup() {
if(popupStatus == 1) { // if value is 1, close popup
$(".single_variation_wrap > div:nth-child(2)").fadeOut("normal");
$(".single_variation_wrap > div:nth-child(4)").fadeOut("normal");
popupStatus = 0; // and set value to 0
}
}
}); // jQuery End

hidding elements in a layout page mvc3

ok so im having a hard time hiding some layout sections (divs in my layout page and im using mvc3).
I have this js fragment which is basically the main logic:
$('.contentExpand').bind('click', function () {
$.cookie('right_container_visible', "false");
});
//Cookies Functions========================================================
//Cookie for showing the right container
if ($.cookie('right_container_visible') === 'false') {
if ($('#RightContainer:visible')) {
$('#RightContainer').hide();
}
$.cookie('right_container_visible', null);
} else {
if ($('#RightContainer:hidden')) {
$('#RightContainer').show();
}
}
as you can see, im hidding the container whenever i click into some links that have a specific css. This seems to work fine for simple tests. But when i start testing it like
.contentExpand click --> detail button click --> .contentExpand click --> [here unexpected issue: the line $.cookie('right_container_visible', null); is read but it doesnt set the vaule to null as if its ignoring it]
Im trying to understand whats the right logic to implement this. Anyone knows how i can solve this?
The simpliest solution is to create variable outside delegate of bind.
For example:
var rightContVisibility = $.cookie('right_container_visible');
$('.contentExpand').bind('click', function () {
$.cookie('right_container_visible', "false");
rightContVisibility = "false";
});
if (rightContVisibility === 'false') {
...
}
The best thing that worked for me was to create an event that can catch the resize of an element. I got this from another post but I dont remember which one. Anyway here is the code for the event:
//Event to catch rezising============================================================================
(function () {
var interval;
jQuery.event.special.contentchange = {
setup: function () {
var self = this,
$this = $(this),
$originalContent = $this.text();
interval = setInterval(function () {
if ($originalContent != $this.text()) {
$originalContent = $this.text();
jQuery.event.handle.call(self, { type: 'contentchange' });
}
}, 100);
},
teardown: function () {
clearInterval(interval);
}
};
})();
//=========================================================================================
//Function to resize the right container============================================================
(function ($) {
$.fn.fixRightContainer = function () {
this.each(function () {
var width = $(this).width();
var parentWidth = $(this).offsetParent().width();
var percent = Math.round(100 * width / parentWidth);
if (percent > 62) {
$('#RightContainer').remove();
}
});
};
})(jQuery);
//===================================================================================================

Resources