I was looking at this article to apply header menu with dropdowns in my mvc5 knockoutjs solution.
https://jdmdigital.co/news/codex/bootstrap-3-secondary-dropdown-menu/
The frontend it looks nice, and it is ok in my solution, however, I cant figure it out how to bind js section to work.
Now when I click on my dropdown parent item, nothing happens, because the js code is not working.
here is my setup of the js (knockoutjs) file.
define(['durandal/system', 'plugins/router', 'durandal/services/logger', 'knockout', 'common', 'plugins/dialog', 'durandal/binder', 'fastclick'],
function (system, router, logger, ko, common, dialog, binder, fs) {
var shell = {
activate: activate,
router: router,
};
// Make Dropdown Submenus possible
$('.dropdown-submenu a.dropdown-submenu-toggle').on("click", function (e) {
$('.dropdown-submenu ul').removeAttr('style');
$(this).next('ul').toggle();
e.stopPropagation();
e.preventDefault();
});
// Clear Submenu Dropdowns on hidden event
$('#bs-navbar-collapse-1').on('hidden.bs.dropdown', function () {
$('.navbar-nav .dropdown-submenu ul.dropdown-menu').removeAttr('style');
});
//...
//...
//OTHER INIT METHODS (not in the scope for this question)
//#region Internal Methods
function activate() {
var result = registerRoutes();
//setRouteGuard();
if (window.cordova) {
window.document.addEventListener("deviceready", function () {
shell.refreshUserData(true);
shell.changeLanguage();
});
} else {
shell.refreshUserData(true);
shell.changeLanguage();
}
shell.isLoading.subscribe(function (newValue) {
//if something gone wrong
if (newValue) {
setTimeout(function () {
//shell.isLoading(false);
}, 10000);
}
});
if (router.activeInstruction().config.moduleId == "viewmodels/parentschedule") {
if (shell.isAnonymousUser() == true) {
shell.isClient(false);
shell.isEmployee(false);
}
else {
shell.isClient(true);
shell.isEmployee(true);
}
//console.log("test");
}
return result;
}
function route(r, moduleId, name, visible, alwaysVisible, role, condition) {
var self = this;
self.route = r;
self.moduleId = moduleId;
self.title = name;
self.visible = visible;
self.nav = true;
self.role = role;
self.condition = condition;
self.mouseover = ko.observable(false);
self.onhover = function () {
self.mouseover(!self.mouseover());
};
self.goToPage = function () {
router.navigate(this.hash);
};
self.alwaysVisible = alwaysVisible;
self.isTouched = ko.observable(false);
self.setTouched = function () {
self.isTouched(true);
return true;
}
self.setUnTouched = function () {
setTimeout(function () {
self.isTouched(false);
}, 200);
return true;
}
self.isActiveMenuItem = ko.computed(function () {
return router.activeInstruction() &&
router.activeInstruction().fragment.indexOf(self.route) > -1
});
return self;
}
//#endregion
});
Related
I have three aspx pages that I wanted to share the same JS file each has its own init function.
Is there a better way to do this?
ASPX Page
<script>
$(document).ready(function () {
ReimbursementDrug.init()
});
</script>
JS Page
var ReimbursementProgram = function () {
return {
init: function () {
GetAllReimbursement();
}
}
}();
var ReimbursementAsset = function () {
return {
init: function () {
GetAllAsset();
}
}
}();
var ReimbursementDrug = function () {
return {
init: function () {
GetAllDrug();
}
}
}();
Give an element on those pages an unique id or class and apply a selector in the .js file.
$('.ReimbursementDrugClass').each(function () {
ReimbursementDrug.init();
});
Or
if ($('#ReimbursementDrugID').length) {
ReimbursementDrug.init();
}
I using Jquery-3.2.1, Jquery-Ui 1.12.1.In my JavaScript file:
window.TruyenOnlineScript = (function () {
var _this = {};
_this.init = function () {
_this.initSearchMobile();
_this.initSidebar();
};
_this.initSearchMobile = function () {
//Open Input Search Mobile
$('.js-open-search-box-mobile').on('click', function (event) {
event.preventDefault();
$('body').addClass('open-search-box');
setTimeout(function () {
$('#js-search-input-mobile').focus()
}, 500);
});
};
_this.initSidebar = function () {
//Open Navbar Moblie
$('.js-open-sidebar').on('click', function (event) {
event.preventDefault();
event.stopPropagation();
$('body').addClass('open-sidebar');
});
};
})();
$('document').ready(function () {
window.TruyenOnlineScript.init();
});
But I got the error "init of undefined":
Can anybody show me how to fix it? Thank you!
You are setting window.TruyenOnlineScript to the return value of an Immediately Invoked Function Expression:
window.TruyenOnlineScript = (function () {
. . .
})();
but that expression doesn't return any value and so window.TruyenOnlineScript winds up being undefined (and that's why you can't call init() on undefined).
You need to have the IIFE return an object for TruyenOnlineScript to reference.
window.TruyenOnlineScript = (function () {
var _this = {};
_this.init = function () {
_this.initSearchMobile();
_this.initSidebar();
};
_this.initSearchMobile = function () {
//Open Input Search Mobile
$('.js-open-search-box-mobile').on('click', function (event) {
event.preventDefault();
$('body').addClass('open-search-box');
setTimeout(function () {
$('#js-search-input-mobile').focus()
}, 500);
});
};
_this.initSidebar = function () {
//Open Navbar Moblie
$('.js-open-sidebar').on('click', function (event) {
event.preventDefault();
event.stopPropagation();
$('body').addClass('open-sidebar');
});
};
return _this; // <-- Now this will be returned
})();
$('document').ready(function () {
window.TruyenOnlineScript.init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Some users have already given you the solution, but I want to show you another way to create the same object. I can't say it's "better", but it's clearer and a little easier to understand:
window.TruyenOnlineScript = {
init: function () {
this.initSearchMobile();
this.initSidebar();
},
initSearchMobile: function () {
//Open Input Search Mobile
$('.js-open-search-box-mobile').on('click', function (event) {
event.preventDefault();
$('body').addClass('open-search-box');
setTimeout(function () {
$('#js-search-input-mobile').focus()
}, 500);
});
},
initSidebar: function () {
//Open Navbar Moblie
$('.js-open-sidebar').on('click', function (event) {
event.preventDefault();
event.stopPropagation();
$('body').addClass('open-sidebar');
});
}
};
I have divs that expand and contract when clicked on. The Masonry library has worked great for initializing the page. The problem I am experiencing is that with the absolute positioning in place from Masonry and the directive below, when divs expand they overlap with the divs below. I need to have the divs below the expanding div move down to deal with the expansion.
My sources are:
http://masonry.desandro.com/
and
https://github.com/passy/angular-masonry/blob/master/src/angular-masonry.js
/*!
* angular-masonry <%= pkg.version %>
* Pascal Hartig, weluse GmbH, http://weluse.de/
* License: MIT
*/
(function () {
'use strict';
angular.module('wu.masonry', [])
.controller('MasonryCtrl', function controller($scope, $element, $timeout) {
var bricks = {};
var schedule = [];
var destroyed = false;
var self = this;
var timeout = null;
this.preserveOrder = false;
this.loadImages = true;
this.scheduleMasonryOnce = function scheduleMasonryOnce() {
var args = arguments;
var found = schedule.filter(function filterFn(item) {
return item[0] === args[0];
}).length > 0;
if (!found) {
this.scheduleMasonry.apply(null, arguments);
}
};
// Make sure it's only executed once within a reasonable time-frame in
// case multiple elements are removed or added at once.
this.scheduleMasonry = function scheduleMasonry() {
if (timeout) {
$timeout.cancel(timeout);
}
schedule.push([].slice.call(arguments));
timeout = $timeout(function runMasonry() {
if (destroyed) {
return;
}
schedule.forEach(function scheduleForEach(args) {
$element.masonry.apply($element, args);
});
schedule = [];
}, 30);
};
function defaultLoaded($element) {
$element.addClass('loaded');
}
this.appendBrick = function appendBrick(element, id) {
if (destroyed) {
return;
}
function _append() {
if (Object.keys(bricks).length === 0) {
$element.masonry('resize');
}
if (bricks[id] === undefined) {
// Keep track of added elements.
bricks[id] = true;
defaultLoaded(element);
$element.masonry('appended', element, true);
}
}
function _layout() {
// I wanted to make this dynamic but ran into huuuge memory leaks
// that I couldn't fix. If you know how to dynamically add a
// callback so one could say <masonry loaded="callback($element)">
// please submit a pull request!
self.scheduleMasonryOnce('layout');
}
if (!self.loadImages){
_append();
_layout();
} else if (self.preserveOrder) {
_append();
element.imagesLoaded(_layout);
} else {
element.imagesLoaded(function imagesLoaded() {
_append();
_layout();
});
}
};
this.removeBrick = function removeBrick(id, element) {
if (destroyed) {
return;
}
delete bricks[id];
$element.masonry('remove', element);
this.scheduleMasonryOnce('layout');
};
this.destroy = function destroy() {
destroyed = true;
if ($element.data('masonry')) {
// Gently uninitialize if still present
$element.masonry('destroy');
}
$scope.$emit('masonry.destroyed');
bricks = [];
};
this.reload = function reload() {
$element.masonry();
$scope.$emit('masonry.reloaded');
};
}).directive('masonry', function masonryDirective() {
return {
restrict: 'AE',
controller: 'MasonryCtrl',
link: {
pre: function preLink(scope, element, attrs, ctrl) {
var attrOptions = scope.$eval(attrs.masonry || attrs.masonryOptions);
var options = angular.extend({
itemSelector: attrs.itemSelector || '.masonry-brick',
columnWidth: parseInt(attrs.columnWidth, 10) || attrs.columnWidth
}, attrOptions || {});
element.masonry(options);
var loadImages = scope.$eval(attrs.loadImages);
ctrl.loadImages = loadImages !== false;
var preserveOrder = scope.$eval(attrs.preserveOrder);
ctrl.preserveOrder = (preserveOrder !== false && attrs.preserveOrder !== undefined);
scope.$emit('masonry.created', element);
scope.$on('$destroy', ctrl.destroy);
}
}
};
}).directive('masonryBrick', function masonryBrickDirective() {
return {
restrict: 'AC',
require: '^masonry',
scope: true,
link: {
pre: function preLink(scope, element, attrs, ctrl) {
var id = scope.$id, index;
ctrl.appendBrick(element, id);
element.on('$destroy', function () {
ctrl.removeBrick(id, element);
});
scope.$on('masonry.reload', function () {
ctrl.scheduleMasonryOnce('reloadItems');
ctrl.scheduleMasonryOnce('layout');
});
scope.$watch('$index', function () {
if (index !== undefined && index !== scope.$index) {
ctrl.scheduleMasonryOnce('reloadItems');
ctrl.scheduleMasonryOnce('layout');
}
index = scope.$index;
});
}
}
};
});
}());
Like with many non-Angular libraries, it appears the answer lies in wrapping the library in an Angular directive.
I haven't tried it out but it appears that is what this person did
You can use angular's $emit, $broadcast, and $on functionality.
Inside your masonry directive link function:
scope.$on('$resizeMasonry', ctrl.scheduleMasonryOnce('layout'));
Inside your masonryBrick directive link function or any other child element:
scope.$emit('$resizeMasonry');
Use $emit to send an event up the scope tree and $broadcast to send an event down the scope tree.
is there any chance to create a function that i can call?
if i'm putting the following lines in the document ready function it works:
Caman("25-02-2014_16-37-13.jpg", "#example-canvas", function () {
this.brightness(brightness);
this.render(function () {
check = this.toBase64();
});
But if i'm doing this i can't call. So I tried this:
function icancall()
{
Caman("25-02-2014_16-37-13.jpg", "#example-canvas", function () {
this.brightness(brightness);
this.render(function () {
check = this.toBase64();
});
}
So i thought i can call this with icancall(); But nothing happened. What am I doing wrong?
What i want do: executing the Caman function on a button click.
I hope you can help me !
function resz(){
Caman("25-02-2014_16-37-13.jpg", "#example-canvas", function () {
try {
this.render(function () {
var image = this.toBase64();
xyz(image); // call that function where you pass filters
});
} catch (e) { alert(e) }
});
}
[Apply CamanJS filters by this function]
function xyz(image){
var filters_k = $('#filters');
filters_k.click(function (e) {
e.preventDefault();
var f = $(this);
if (f.is('.active')) {
// Apply filters only once
return false;
}
filters_k.removeClass('active');
f.addClass('active');
var effect = $.trim(f[0].id);
Caman(canvasID, img, function () {
if (effect in this) {
this.revert(false);
this[effect]();
this.render();
}
});
});
}
I know my way around several programming languages but am struggling understanding Javascript and how it's used in mobile apps. I'm developing for BlackBerry and a using the BlackBerry 10 jQuery Mobile Theme. I'm looking at the App.js from the samples and am confused as to what the App object is.
App = {};
App.init = function () {
console.log("App Init");
App.utils.metaHack();
$("#activity").live("pageinit", function(){
App.page.activity.init();
});
$("#bb_activity").live("pageinit", function(){
App.page.bb_activity.init();
});
$("#progressPage").live("pageinit", function(){
App.page.progress.init();
});
$("#sliderPage, #sliderPageDark").live("pageinit", function(){
App.page.slider.init();
});
$("#togglePage, #togglePageDark").live("pageinit", function(){
App.page.toggle.init();
});
$("#actionBarSample").live("pageinit", function() {
App.page.actionBarSample.init();
});
$('#applicationMenu').live("pageinit", function() {
App.page.applicationMenu.init();
});
}
App.utils = {
metaHack: function () {
var meta = document.createElement("meta");
meta.setAttribute('name','viewport');
meta.setAttribute('content','initial-scale='+ (1/window.devicePixelRatio) + ',user-scalable=no');
document.getElementsByTagName('head')[0].appendChild(meta);
}
}
App.page = {
activity: {},
bb_activity: {},
progress: {},
slider: {},
toggle: {},
actionBarSample: {},
applicationMenu: {}
}
App.page.activity.init = function() {
$('#show').on('click', function () {
$.mobile.loading('show');
});
$('#text').on('click', function() {
$.mobile.loading('show', {
text: 'Loading',
textVisible: true,
textonly: true,
theme: 'a'
});
});
$('#swatch-a').on('click', function() {
$.mobile.loading( 'show', {
text: 'Loading',
textVisible: true,
theme: 'a'
});
});
$('#swatch-a-notext').on('click', function() {
$.mobile.loading( 'show', {
theme: 'a'
});
});
$('#swatch-c').on('click', function() {
$.mobile.loading( 'show', {
text: 'Loading',
textVisible: true,
theme: 'c'
});
});
$('#swatch-c-notext').on('click', function() {
$.mobile.loading( 'show', {
theme: 'c'
});
});
$('#hide').on('click', function () {
$.mobile.loading('hide');
});
}
App.page.bb_activity.init = function() {
console.log("bb_activity");
$('#throttle').on('change', function () {
console.log("throttle");
var speed = $('#throttle').val();
$('#speedTest').activityindicator('speed', speed+'s');
});
}
App.page.progress.init = function() {
var p = 0;
var error = pause = false;
function watchProgress() {
if( p > 100 || error || pause) {
return;
}
$('#rogress').progressbar("setValue", p);
p+= 4;
setTimeout(watchProgress, 100);
}
$('#start').on('vclick', function () {
error = false;
watchProgress();
});
$('#error').on('vclick', function () {
$('#rogress').progressbar("setError", error = !error);
});
$('#pause').on('vclick', function () {
$('#rogress').progressbar("pause", pause = !pause);
});
$('#reset').on('vclick', function () {
p = 0;
error = pause = false;
$('#rogress').progressbar("setValue", p);
});
}
App.page.slider.init = function() {
$('#slider-disabled').slider('disable');
$('#slider-disabled-highlight').slider('disable');
}
App.page.toggle.init = function() {
console.log("toggle init");
$('#flip-disabled').slider('disable');
}
App.page.actionBarSample.init = function() {
var $tabo = $("#tover"),
overflowState = $tabo.hasClass("noContent");
$("#left").on("panelbeforeopen", function() {
//Save the state of the overflow button
overflowState = $tabo.hasClass("noContent");
$tabo.addClass("noContent");
})
.on("panelbeforeclose", function() {
//Put the overflow button into the correct state
if(!overflowState) {
$tabo.removeClass("noContent");
}
});
//Handle overflow menu clicks
$(".bb10-panel").bind("vclick", function() {
//Close the panel
$(this).panel("close");
});
$("#left li").bind("vclick", function() {
//Clear the active state from any other buttons that may have been set to active
$(this).siblings().removeClass("ui-btn-active");
//Add the active state to the selected button
$(this).addClass("ui-btn-active");
//Clear the contents of the tab overflow button
//Add class to put the tab overflow icon in the correct position
//Clear the active state from all tab buttons in action bar
$('[data-role="tab"], [data-role="tab-overflow"]').removeClass("active");
});
$(".inBar").bind("vclick", function() {
//Set the active state to the tab in the actionbar
$('#' + this.id.slice(0, 2)).addClass("active");
$tabo.addClass("noContent").empty();
overflowState = true;
});
$(".notInBar").bind("vclick", function() {
//Set the active state to the tab overflow button
$tabo.empty()
.addClass("active")
.html('<img src="img/generic_81_81_placeholder.png" alt=""><p>' + $(this).text() + '</p>')
.removeClass("noContent");
overflowState = false;
});
$("[data-role='tab']").bind("vclick", function() {
//Change page on tab click
if($(this).data("href")) {
$.mobile.changePage( $(this).data("href"), { transition: "slideup"} );
}
});
}
App.page.applicationMenu.init = function() {
if(typeof blackberry != 'undefined'){
blackberry.event.addEventListener('swipedown', function(){
$('#top').panel("open");
});
$('#menuBtn').css('display','none');
}
else{
$('#simulInst').css('display','none');
}
}
App.init();
Is App an object specific to Blackberry? I did some dabbling and made a small app but didn't use App or init anything.
App in this example is defined at the top:
App = {};
So it's just a new plain old JavaScript object (dictionary), which they then define functions and data to it e.g. App.utils = ....
You can try it out on a browser, press F12 and then go to the console (ESC) and type e.g. blah = {} and you will see a new object created with the name blah. Everything is an object in JavaScript apparently.
Read more
http://www.w3schools.com/js/js_objects.asp