KnockoutJs call function in other viewmodel of applyBindings - javascript

On a page I'm calling ko.applyBindings twice to iniate 2 view models. When viewModelOne saves successfully, I want to reload the other view model as some data is added in the backend as they are loosely linked.
Now I'm trying to call viewModelTwo.reloadData in saveSuccess() but I keep getting the error that it can't find the function whatever I try.
(Uncaught TypeError: viewModelTwo.reloadData is not a function)
What is the correct way of calling a function from the other viewmodel in KnockoutJs? Could anyone point me in the right direction?
var viewModelOne = (function () {
function reloadData(url) {
...
}
function saveSuccess(){
viewModelTwo.reloadData('');
}
});
var viewModelTwo = (function () {
function reloadData(url) {
...
}
});
ko.applyBindings(viewModelOne, document.getElementById("modelOneContainer"));
ko.applyBindings(viewModelTwo, document.getElementById("modelTwoContainer"));

You could use a constructor function:
function ViewModelOne() {
var vm = this;
vm.reloadData = function() {
console.log('vm1 reloaddata');
}
}
var vm1 = new ViewModelOne();
function ViewModelTwo() {
var vm = this;
vm.reloadData = function() {
vm1.reloadData();
console.log('vm2 reloaddata');
}
}
var vm2 = new ViewModelTwo();
ko.applyBindings(vm1, document.getElementById("modelOneContainer"));
ko.applyBindings(vm2, document.getElementById("modelTwoContainer"));
vm2.reloadData();
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div id="modelOneContainer"></div>
<div id="modelTwoContainer"></div>

Related

How to trigger function when control is loaded

I work on my angularjs project.
Here is my cotroller:
(function () {
"use strict";
angular.module("dashboard").controller('dashboardController', ["$scope", "dashboardServices", dashboardController]);
function dashboardController($scope, dashboardServices) {
$scope.month = new Date().getMonth()+1;
$scope.year = new Date().getFullYear();
$scope.getRecords = function () {
dashboardServices.getRecords($scope.year, $scope.month).then(function (response) {
var result = dashboardServices.convert2json(response.data);
$scope.report = result.ArrayOfDepartmentReport;
});
}
}
})();
How to make function $scope.getRecords to be triggered when controll is loaded.
Execution of your controller code happens only when the controller is loaded.
Put $scope.getRecords() at the bottom of the controller.

ion-toggle ng-change does not trigger properly with controller + service structure

I've created a list of toggles to select bluetooth devices and connect it, and I've created a controller.js and service.js for them. However, the ng-changeonly triggers when ion-toggles first loaded in view, and were not triggering for changes afterwards.
Here is my snippet of setting.html:
<ion-toggle ng-repeat="item in devicesList"
ng-model="item.checked"
ng-change="connectDevice(devicesList)">
{{ item.address }}
</ion-toggle>
and here is my settingController.js:
(function () {
'use strict';
angular.module('i18n.setting').controller('SettingController', SettingController);
SettingController.$inject = ['$scope','SettingService'];
function SettingController($scope, SettingService) {
$scope.devicesList = [];
$scope.scanDevices = SettingService.scanDevices($scope.devicesList);
$scope.connectDevice = SettingService.connectDevice($scope.devicesList);
};
})();
and here is my settingService.js:
(function(){
'use strict';
angular.module('i18n.setting').service('SettingService', SettingService);
SettingService.$inject = [];
function SettingService(){
var self = this;
this.scanDevices = function(devicesCollection) {
window.bluetoothSerial.discoverUnpaired(function(devices) {
console.log("in discoverUnpaired callback, setting page");
devices.forEach(function(device) {
console.log(device.name);
device.checked = false;
devicesCollection.push(device);
});
}, function(error) {
console.log("in discoverUnpaired error function");
console.log(error);
});
};
this.connectDevice = function(devicesCollection) {
console.log(devicesCollection);
console.log("In connectDevice");
for (var i =0; i<devicesCollection.length; i++)
{
console.log(devicesCollection[i].id + " " + devicesCollection[i].checked);
if (devicesCollection[i].checked == true)
{
console.log(devicesCollection[i].name);
window.bluetoothSerial.connect(devicesCollection[i].address,
function(data) {console.log("This device is"+macaddress); console.log(data);},
function(error) {console.log(error);});
}
}
};
}
})();
And if I define this function directly in settingController.js, it's working properly and can detect every change of the toggle. Also, I noticed that my scanDevices function will be triggered even if I don't click the button. I don't know why is it. Will there be someone tell me what cause is it? Any help, thanks
The controller should put the service functions on the scope; not invocations of the service functions.
(function () {
'use strict';
angular.module('i18n.setting').controller('SettingController', SettingController);
SettingController.$inject = ['$scope','SettingService'];
function SettingController($scope, SettingService) {
$scope.devicesList = [];
//$scope.scanDevices = SettingService.scanDevices($scope.devicesList);
$scope.scanDevices = SettingService.scanDevices;
//$scope.connectDevice = SettingService.connectDevice($scope.devicesList);
$scope.connectDevice = SettingService.connectDevice;
};
})();
Since the scanDevices function has no return statement, scanDevices($scope.deviceList) returns undefined. Thus $scope.scanDevices was getting set to undefined.
Update
Can you also explain why scanDevices get invoked before I press the Scan button?
Which was bind to:
<button class="button button-stable"
ng-click="scanDevices(devicesList)">Scan Devices
</button>
By binding an invocation of the function to the scope variable instead of the function itself:
//ERRONEOUS
$scope.scanDevices = SettingService.scanDevices($scope.devicesList);
//CORRECT
$scope.scanDevices = SettingService.scanDevices;
The expression SettingService.scanDevices($scope.devicesList) invokes the function before the button is clicked. And assigns undefined to the $scope.scanDevices variable.

Can't bind or render Rich Text from REST with Knockout

I'm getting data back and it does render Title, but can't seem to render rich text.
markup:
<div id="bodyarea">
<div data-bind=foreach:list>
<span data-bind="text:Title" />
<div data-bind="html: RichData"></div>
</div>
</div>
<p id="myarea"></p>
ko:
function LoadLists() {
var listItems = [];
var count = 0;
$.getJSON("https://myserver.com/sites/knockout/_api/lists/getbytitle('List%20One')/items?$filter=Title eq
'zzzz'",
function (data, textstatus, jqXHR) {
$(data.value).each(function (index, item) {
count++;
var koItem = {};
koItem.Title = item.Title;
koItem.RichData = item.Rich;
listItems.push(koItem);
if (data.value.length == count) {
var vm =
{
list: ko.observableArray(listItems)
};
ko.applyBindings(vm, document.getElementById("bodyarea"));
}
})
});
}
$(document).ready(function () { LoadLists(); });
In general, with knockout, you should not:
Call applyBindings more than once
Call applyBindings inside an ajax call
Create a viewModel as a plain object (usually, sometimes it's alright)
Do knockout databinding inside jQuery event handlers.
Code:
// this is a reusable view model for each item. it takes a raw item from the ajax return, and creates observables for each property.
var ListItem = function (item) {
var self = this;
self.Title = ko.observable(item.Title);
self.RichData = ko.observable(item.Rich);
}
// Your viewModel. Constructor-esque syntax is pretty standard.
var ViewModel = function () {
var self = this;
// this is your list array.
self.list = ko.observableArray();
// This is a your reusable function to load lists, when it returns, it maps each item
// in data.value to a ListItem viewModel and puts them all in the lists observableArray
self.loadList = function() {
$.getJSON('yourUrl', function(data) {
var items = data.value.map(function(item) { return new ListItem(item); });
self.list(items);
}
};
};
// When the document is ready, create a view model and apply bindings once. Then call loaLists to initialize
$(document).ready(function () {
var vm = new ViewModel();
ko.applyBindings(vm);
vm.loadList();
});

AngularJS : How to run JavaScript from inside Directive after directive is compiled and linked

I have a responsive template that I am trying to use with my Angularjs app. This is also my first Angular app so I know I have many mistakes and re-factoring in my future.
I have read enough about angular that I know DOM manipulations are suppose to go inside a directive.
I have a javascript object responsible for template re-sizes the side menu and basically the outer shell of the template. I moved all of this code into a directive and named it responsive-theme.
First I added all the methods that are being used and then I defined the App object at the bottom. I removed the function bodies to shorten the code.
Basically the object at the bottom is a helper object to use with all the methods.
var directive = angular.module('bac.directive-manager');
directive.directive('responsiveTheme', function() {
return {
restrict: "A",
link: function($scope, element, attrs) {
// IE mode
var isRTL = false;
var isIE8 = false;
var isIE9 = false;
var isIE10 = false;
var sidebarWidth = 225;
var sidebarCollapsedWidth = 35;
var responsiveHandlers = [];
// theme layout color set
var layoutColorCodes = {
};
// last popep popover
var lastPopedPopover;
var handleInit = function() {
};
var handleDesktopTabletContents = function () {
};
var handleSidebarState = function () {
};
var runResponsiveHandlers = function () {
};
var handleResponsive = function () {
};
var handleResponsiveOnInit = function () {
};
var handleResponsiveOnResize = function () {
};
var handleSidebarAndContentHeight = function () {
};
var handleSidebarMenu = function () {
};
var _calculateFixedSidebarViewportHeight = function () {
};
var handleFixedSidebar = function () {
};
var handleFixedSidebarHoverable = function () {
};
var handleSidebarToggler = function () {
};
var handleHorizontalMenu = function () {
};
var handleGoTop = function () {
};
var handlePortletTools = function () {
};
var handleUniform = function () {
};
var handleAccordions = function () {
};
var handleTabs = function () {
};
var handleScrollers = function () {
};
var handleTooltips = function () {
};
var handleDropdowns = function () {
};
var handleModal = function () {
};
var handlePopovers = function () {
};
var handleChoosenSelect = function () {
};
var handleFancybox = function () {
};
var handleTheme = function () {
};
var handleFixInputPlaceholderForIE = function () {
};
var handleFullScreenMode = function() {
};
$scope.App = {
//main function to initiate template pages
init: function () {
//IMPORTANT!!!: Do not modify the core handlers call order.
//core handlers
handleInit();
handleResponsiveOnResize(); // set and handle responsive
handleUniform();
handleScrollers(); // handles slim scrolling contents
handleResponsiveOnInit(); // handler responsive elements on page load
//layout handlers
handleFixedSidebar(); // handles fixed sidebar menu
handleFixedSidebarHoverable(); // handles fixed sidebar on hover effect
handleSidebarMenu(); // handles main menu
handleHorizontalMenu(); // handles horizontal menu
handleSidebarToggler(); // handles sidebar hide/show
handleFixInputPlaceholderForIE(); // fixes/enables html5 placeholder attribute for IE9, IE8
handleGoTop(); //handles scroll to top functionality in the footer
handleTheme(); // handles style customer tool
//ui component handlers
handlePortletTools(); // handles portlet action bar functionality(refresh, configure, toggle, remove)
handleDropdowns(); // handle dropdowns
handleTabs(); // handle tabs
handleTooltips(); // handle bootstrap tooltips
handlePopovers(); // handles bootstrap popovers
handleAccordions(); //handles accordions
handleChoosenSelect(); // handles bootstrap chosen dropdowns
handleModal();
$scope.App.addResponsiveHandler(handleChoosenSelect); // reinitiate chosen dropdown on main content resize. disable this line if you don't really use chosen dropdowns.
handleFullScreenMode(); // handles full screen
},
fixContentHeight: function () {
handleSidebarAndContentHeight();
},
setLastPopedPopover: function (el) {
lastPopedPopover = el;
},
addResponsiveHandler: function (func) {
responsiveHandlers.push(func);
},
// useful function to make equal height for contacts stand side by side
setEqualHeight: function (els) {
var tallestEl = 0;
els = jQuery(els);
els.each(function () {
var currentHeight = $(this).height();
if (currentHeight > tallestEl) {
tallestColumn = currentHeight;
}
});
els.height(tallestEl);
},
// wrapper function to scroll to an element
scrollTo: function (el, offeset) {
pos = el ? el.offset().top : 0;
jQuery('html,body').animate({
scrollTop: pos + (offeset ? offeset : 0)
}, 'slow');
},
scrollTop: function () {
App.scrollTo();
},
// wrapper function to block element(indicate loading)
blockUI: function (ele, centerY) {
var el = jQuery(ele);
el.block({
message: '<img src="./assets/img/ajax-loading.gif" align="">',
centerY: centerY !== undefined ? centerY : true,
css: {
top: '10%',
border: 'none',
padding: '2px',
backgroundColor: 'none'
},
overlayCSS: {
backgroundColor: '#000',
opacity: 0.05,
cursor: 'wait'
}
});
},
// wrapper function to un-block element(finish loading)
unblockUI: function (el) {
jQuery(el).unblock({
onUnblock: function () {
jQuery(el).removeAttr("style");
}
});
},
// initializes uniform elements
initUniform: function (els) {
if (els) {
jQuery(els).each(function () {
if ($(this).parents(".checker").size() === 0) {
$(this).show();
$(this).uniform();
}
});
} else {
handleUniform();
}
},
updateUniform : function(els) {
$.uniform.update(els);
},
// initializes choosen dropdowns
initChosenSelect: function (els) {
$(els).chosen({
allow_single_deselect: true
});
},
initFancybox: function () {
handleFancybox();
},
getActualVal: function (ele) {
var el = jQuery(ele);
if (el.val() === el.attr("placeholder")) {
return "";
}
return el.val();
},
getURLParameter: function (paramName) {
var searchString = window.location.search.substring(1),
i, val, params = searchString.split("&");
for (i = 0; i < params.length; i++) {
val = params[i].split("=");
if (val[0] == paramName) {
return unescape(val[1]);
}
}
return null;
},
// check for device touch support
isTouchDevice: function () {
try {
document.createEvent("TouchEvent");
return true;
} catch (e) {
return false;
}
},
isIE8: function () {
return isIE8;
},
isRTL: function () {
return isRTL;
},
getLayoutColorCode: function (name) {
if (layoutColorCodes[name]) {
return layoutColorCodes[name];
} else {
return '';
}
}
};
}
};
});
Originally the App.init() object method would be called at the bottom of any regular html page, and I have others that do certain things also that would be used on specific pages like Login.init() for the login page and so forth.
I did read that stackoverflow post
"Thinking in AngularJS" if I have a jQuery background? and realize that I am trying to go backwards in a sense, but I want to use this template that I have so I need to retro fit this solution.
I am trying to use this directive on my body tag.
<body ui-view="dashboard-shell" responsive-theme>
<div class="page-container">
<div class="page-sidebar nav-collapse collapse" ng-controller="SidemenuController">
<sidemenu></sidemenu>
</div>
<div class="page-content" ui-view="dashboard">
</div>
</div>
</body>
So here is my problem. This kinda sorta works. I don't get any console errors but when I try to use my side menu which the javascript for it is in the directive it doesn't work until I go inside the console and type App.init(). After that all of the template javascript works. I want to know how to do responsive theme stuff in these directives. I have tried using it both in the compile and link sections. I have tried putting the code in compile and link and calling the $scope.App.init() from a controller and also at the bottom after defining everything. I also tried putting this in jsfiddle but can't show a true example without having the console to call App.init().
My end design would be having some way to switch the pages through ui-router and when a route gets switched it calls the appropriate methods or re-runs the directive or something. The only method that will run on every page is the App.init() method and everything else is really page specific. And technically since this is a single page app the App.init() only needs to run once for the application. I have it tied to a parent template inside ui-router and the pages that will switch all use this shell template. There are some objects that need to access other to call their methods.
Im sorry in advance for maybe a confusing post. I am struggling right now trying to put together some of the ways that you do things from an angular perspective. I will continue to edit the post as I get responses to give further examples.
You said I have read enough about angular that I know DOM manipulations are suppose to go inside a directive but it sounds like you missed the point of a directive. A directive should handle DOM manipulation, yes, but not one directive for the entire page. Each element (or segment) of the page should have its own directive (assuming DOM manip needs to be done on that element) and then the $controller should handle the interactions between those elements and your data (or model).
You've created one gigantic directive and are trying to have it do way too much. Thankfully, you've kinda sorta designed your code in such a way that it shouldn't be too hard to break it up into several directives. Basically, each of your handle functions should be its own directive.
So you'd have something like:
.directive('sidebarMenu', function(){
return {
template: 'path/to/sidebar/partial.html',
link: function(scope, elem, attrs){
// insert the code for your 'handleSidebarMenu()' function here
}
};
})
.directive('horizontalMenu', function(){
return {
template: 'path/to/horizontal/partial.html',
link: function(scope, elem, attrs){
// insert the code for your 'handleHorizontalMenu()' function here
}
};
})
and then your view would look something like:
<body ui-view="dashboard-shell" responsive-theme>
<div class="page-container">
<div class="page-sidebar nav-collapse collapse">
<horizontal-menu></horizontal-menu>
<sidebar-menu></sidebar-menu>
</div>
<div class="page-content" ui-view="dashboard">
</div>
</div>
</body>
And then you don't need a SidebarmenuController because your controller functions shouldn't be handling DOM elements like the sidebar. The controller should just handling the data that you're going to display in your view, and then the view (or .html file) will handle the displaying and manipulation of that data by its use of the directives you've written.
Does that make sense? Just try breaking that huge directive up into many smaller directives that handle specific elements or specific tasks in the DOM.

Reference to variable is undefined

I'm try to call a function that I know exists on a variable but for some reason I just can't call in from within the passed function onUpdate - Any ideas guys - sorry for the newbness
//set up the mirror when view is expanded
function attachMirrorListener(section, mirror) {
var textarea = document.getElementById(mirror.attr('id'));
var input = $(mirror.data('input'));
var myCodeMirror;
section.click(function() {
if(section.hasClass('open') && !section.hasClass('mirror-added')) {
section.addClass('mirror-added');
input.attr('value','test value!!');
myCodeMirror = CodeMirror.fromTextArea(textarea, {
onUpdate : function(){ myCodeMirror.save(); //does not work here!!
},
});
}
console.log(myCodeMirror);
myCodeMirror.save(); //works here
});
}
});
UPDATE
I tried rearranging the code, still not working
jQuery(document).ready(function($) {
var _codeMirror;
//setup code-mirror
$('.customize-section').each(function() {
var section = $(this);
var mirror = section.find('textarea.wpec-tc-code-mirror');
if(mirror.length > 0) {
attachMirrorListener(section, mirror);
}
});
//set up the mirror when view is expanded
function attachMirrorListener(section, mirror) {
var textarea = document.getElementById(mirror.attr('id'));
var input = $(mirror.data('input'));
section.click(function() {
if(section.hasClass('open') && !section.hasClass('mirror-added')) {
section.addClass('mirror-added');
_codeMirror = CodeMirror.fromTextArea(textarea, {
onUpdate : codemirrorcallback,
});
}
});
function codemirrorcallback() {
_codeMirror.save();
input.val(escape(textarea.value));
}
}
});
Here is the error log from the chrome console
Uncaught TypeError: Cannot call method 'save' of undefined codemirror.js:26
codemirrorcallback codemirror.js:26
endOperation codemirror.js:1864
instance.(anonymous function) codemirror.js:1871
CodeMirror codemirror.js:95
CodeMirror.fromTextArea codemirror.js:2114
(anonymous function) codemirror.js:19
f.event.dispatch load-scripts.php:3
f.event.add.h.handle.i
The assignment operator works from right to left. So, when you're calling myCodeMirror.save() the first time, myCodeMirror is still undefined.
var myCodeMirror; //undefined
myCodeMirror = CodeMirror.fromTextArea(textarea, {
onUpdate : function() {
myCodeMirror.save(); //still undefined
}
});
You should instead be calling this.save() from within the inner onUpdate function.

Categories

Resources