How call event in correct way in Module Pattern edition - structure

After reading an article https://css-tricks.com/how-do-you-structure-javascript-the-module-pattern-edition/ I did something similar in my project - created the structure:
var SomeStructure = {
var1: $('#tag1'),
init: function() {
this.var1.on('click', function (e) {
SomeStructure.mouseClick(e);
});
},
mouseClick: function(e) {
e.preventDefault();
alert("tag clicked");
}
}
SomeStructure.init();
div {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tag1">Click me!</div>
My code is working, but I wondering if it's possible rewrite the code:
this.var1.on('click', function (e) {
SomeStructure.mouseClick(e);
});
so that the call of function mouseClick after clicking the $('#tag1') in some more neat way without anonymous function in one row, something like that:
this.var1.on('click', this.mouseClick);
But this way isn't right without e..
Thank you in advance.

I have to add a new function ListenEvents for events listening, so that a lot of new listeners could be added inside to make clear workflow object (as described here http://derickbailey.com/2015/08/07/making-workflow-explicit-in-javascript/) :
`var SomeStructure = {
var1: $('#tag1'),
init: function() {
this.ListenEvents();
},
ListenEvents: function() {
self = SomeStructure;
self.var1.on('click', self.mouseClick);
},
mouseClick: function() {
alert("tag clicked");
}
}
SomeStructure.init();`

Related

VueJS Leaflet 'moveend' fires multiple times

Ask for help from the community. For two weeks I can not overcome the problem with repeated firing of 'mooveend' in the project. I have tried all the advice given here. Here's what I've read and researched already, but it didn't work for me.
This is one of the tips:
moveend event fired many times when page is load with Leaflet
<template>
<div id="map"></div>
</template>
<script>
export default {
name: "ObjectMapView",
props: ['coordinate'],
data: function () {
return {
map: null,
addressPoints: null,
markers: null,
}
},
mounted: function() {
this.initializedMap();
},
watch: {
coordinate: function (val) {
this.run();
}
},
methods: {
initializedMap: function () {
this.map = L.map('map').setView([52.5073390000,5.4742833000], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(this.map);
this.markers = L.markerClusterGroup();
},
run: function () {
var map = this.map;
var markers = this.markers;
var getAllObjects = this.coordinate;
var getBoundsMarkers;
//Clearing Layers When Switching a Filter
markers.clearLayers();
this.addressPoints = getAllObjects.map(function (latlng){
return [latlng.latitude, latlng.longitude, latlng.zip, latlng.object_id, latlng.archived];
});
map.addLayer(markers);
//We give to the map only those coordinates that are in the zone of visibility of the map during the first
getBoundsMarkers = getAllObjects.filter((coord) => {
if(!coord.latitude && !coord.longitude){
return false;
}
return map.getBounds().contains(L.latLng(coord.latitude, coord.longitude));
});
/*
Responds to changing the boundaries of the map visibility zone and
transmits a list of coordinates that are in the visibility zone
*/
console.log('getAllObjects_1', getAllObjects);
map.on('moveend', function() {
console.log('moveend');
console.log('getAllObjects_2', getAllObjects);
getBoundsMarkers = getAllObjects.filter((coord) => {
if(!coord.latitude && !coord.longitude){
return false;
}
return map.getBounds().contains(L.latLng(coord.latitude, coord.longitude));
});
eventHub.$emit('sendMarkers', getBoundsMarkers);
});
// In the loop, we iterate over the coordinates and give them to the map
for (var i = 0; i < this.addressPoints.length; i++) {
var a = this.addressPoints[i];
var title = '' + a[2] + ''; //bubble
var marker = L.marker(new L.LatLng(a[0], a[1]), {
title: title
});
marker.bindPopup(title);
markers.addLayer(marker);
}
eventHub.$emit('sendMarkers', getBoundsMarkers);
}
}
}
</script>
<style scoped>
#map {
width: 97%;
height: 100%;
}
</style>
I figured it out myself.
The 'zoomend' and 'dragend' option didn't work for me. I searched a lot for a suitable option and realized that the "moveend" event fires several times because this event is created every time you move the map. Therefore it is necessary to stop this event. I got out of the situation in this way. Immediately after the map was initialized, I wrote:
map.off('moveend');
and for me it worked. Now it works fine. I will be very happy if this is useful to someone.

Dojo instances of same widgets are not saparated

I have built a Dojo Widget for creating a list by entering values. the widget code is:
define(["dojo/_base/declare", "dijit/_WidgetBase", "dijit/_TemplatedMixin", 'dojo/text!apps/orders/templates/multiAddList.html', "dojo/dom", "dojo/on", "dojo/dom-construct", "dojo/dom-class", "dojo/query", "dijit/focus"],
function (declare, WidgetBase, TemplatedMixin, html, dom, on, domConstruct, domClass, query, focusUtil) {
return declare([WidgetBase, TemplatedMixin], {
templateString: html,
postCreate: function () {
this.inherited(arguments);
var that = this;
},
_checkIfEnter: function (e) {
if (e.which == 13) {
this._addUser();
}
},
_addUser: function () {
domClass.remove(this.ulAdded, "hidden");
var textToAdd = this.userTextToAdd.value;
var li = domConstruct.create("li", {}, this.ulAdded);
domConstruct.create("span", {innerHTML: textToAdd}, li);
var spanX = domConstruct.create("span", {class: 'icon-x right'}, li);
this.itemsArray.push(textToAdd);
this.userTextToAdd.value = "";
focusUtil.focus(this.userTextToAdd);
var that = this;
on(spanX, "click", function () {
domConstruct.destroy(li);
that.itemsArray.splice(that.itemsArray.indexOf(textToAdd), 1);
if (that.itemsArray.length == 0) {
domClass.add(that.ulAdded, "hidden");
}
});
},
itemsArray: []
});
});
It is all OK. However - when I instantiate it twice on same dialog like this:
allowedDomains = new MultiAddList();
allowedDomains.placeAt(dom.byId('allowedDomains'), 0);
pdlEmails = new MultiAddList();
pdlEmails.placeAt(dom.byId('pdlEmails'), 0);
and then asking for allowedDomains.itemsArray() or pdlEmails.itemsArray() - I get the same list (as if it is the same instance) - althought in the UI presentation - he adds the list items separately and correctly.
Obviously, I am doing something wrong although I followed Dojo examples.
Does anyone know what I should do in order to make it work?
Thanks
When you make a dojo class using declare, object and array members are static, meaning they are shared across instances, so I would suggest doing itemsArray: null and then this.itemsArray = [] in the constructor or postCreate somewhere.
Everything else looks fine, although I too would have a preference for using hitch, your solution is perfectly fine.
Sorry for just giving you a hint, but you might want to look at the dojo.hicth()-function, as an alternative to the "this-that" contruction
on(spanX, "click", dojo.hitch(this, function () {
domConstruct.destroy(li);
this.itemsArray.splice(this.itemsArray.indexOf(textToAdd), 1);
if (this.itemsArray.length == 0) {
domClass.add(this.ulAdded, "hidden");
}
}));
The on-construct is a good one, but just testing this kind of construct might tell you whether that is the problem or not.
_addUser: function () {
.....
.....
dojo.connect(spanX, "click", this, this.spanClicked);
or
dojo.connect(spanX, "click", dojo.hitch(this, this.spanClicked);
},
spanClicked: function(args) {
domConstruct.destroy(li); //need to keep some reference to li
this.itemsArray.splice(this.itemsArray.indexOf(textToAdd), 1);
if (that.itemsArray.length == 0) {
domClass.add(this.ulAdded, "hidden");
}
}

Non closable dialogbox from Extension Library

I'm creating a dialogbox from ExtLib and I want to prevent users to press Escape or click on X icon.
I've checked several posts about same implementation but none of them using a Dialogbox from ExtLib.
I was able to hide icon with CSS and I'm trying with dojo.connect to prevent the use of Escape key:
XSP.addOnLoad(function(){
dojo.connect(dojo.byId("#{id:dlgMsg}"), "onkeypress", function (evt) {
if(evt.keyCode == dojo.keys.ESCAPE) {
dojo.stopEvent(evt);
}
});
});
Note I'm able to get it working only if I create my dialogbox manually and not from ExtLib; then I can use for example:
dojo.connect(dojo.byId("divDlgLock"), "onkeypress", function (evt) {
if(evt.keyCode == dojo.keys.ESCAPE) {
dojo.stopEvent(evt);
}
});
Any ideas?
By adding an output script block you can extend the existing declaration:
<xp:scriptBlock id="scriptBlockNonCloseableDialog">
<xp:this.value>
<![CDATA[
dojo.provide("extlib.dijit.OneUIDialogNonCloseableDialog");
dojo.require("extlib.dijit.Dialog");
dojo.declare(
"extlib.dijit.OneUIDialogNonCloseableDialog",
extlib.dijit.Dialog,
{
baseClass: "",
templateString: dojo.cache("extlib.dijit", "templates/OneUIDialog.html"),
disableCloseButton: true,
_onKey: function(evt){
if(this.disableCloseButton &&
evt.charOrCode == dojo.keys.ESCAPE) return;
this.inherited(arguments);
},
_updateCloseButtonState: function(){
dojo.style(this.closeButtonNode,
"display",this.disableCloseButton ? "none" : "block");
},
postCreate: function(){
this.inherited(arguments);
this._updateCloseButtonState();
dojo.query('form', dojo.body())[0].appendChild(this.domNode);
},
_setup: function() {
this.inherited(arguments);
if (this.domNode.parentNode.nodeName.toLowerCase() == 'body')
dojo.query('form', dojo.body())[0].appendChild(this.domNode);
}
}
);
// This is used by the picker dialog to grab the correct UI
XSP._dialog_type="extlib.dijit.OneUIDialogNonCloseableDialog";
]]>
</xp:this.value>
</xp:scriptBlock>

Routing/Modularity in Dojo (Single Page Application)

I worked with backbone before and was wondering if there's a similar way to achieve this kind of pattern in dojo. Where you have a router and pass one by one your view separately (like layers) and then you can add their intern functionality somewhere else (e.g inside the view) so the code is very modular and can be change/add new stuff very easily. This code is actually in jquery (and come from a previous project) and it's a "common" base pattern to develop single application page under jquery/backbone.js .
main.js
var AppRouter = Backbone.Router.extend({
routes: {
"home" : "home"},
home: function(){
if (!this.homeView) {
this.homeView= new HomeView();
}
$('#content').html(this.homeView.el);
this.homeView.selectMenuItem('home-link');
}};
utils.loadTemplate(['HomeView'], function() {
app = new AppRouter();
Backbone.history.start();
});
utils.js
loadTemplate: function(views, callback) {
var deferreds = [];
$.each(views, function(index, view) {
if (window[view]) {
deferreds.push($.get('tpl/' + view + '.html', function(data) {
window[view].prototype.template = _.template(data);
}));
} else {
alert(view + " not found");
}
});
$.when.apply(null, deferreds).done(callback);
}};
HomeView.js
window.HomeView = Backbone.View.extend({
initialize:function () {
this.render();
},
render:function () {
$(this.el).html(this.template());
return this;
}
});
And basically, you just pass the html template. This pattern can be called anywhere with this link:
<li class="active"><i class="icon-home"></i> Dashboard</li>
Or, what is the best way to implement this using dojo boilerplate.
The 'boilerplate' on this subject is a dojox.mvc app. Reference is here.
From another aspect, see my go at it a while back, ive setup an abstract for 'controller' which then builds a view in its implementation.
Abstract
Then i have an application controller, which does following on its menu.onClick
which fires loading icon,
unloads current pane (if forms are not dirty)
loads modules it needs (defined 'routes' in a main-menu-store)
setup view pane with a new, requested one
Each view is either simply a server-html page or built with a declared 'oocms' controller module. Simplest example of abstract implementation here . Each implements an unload feature and a startup feature where we would want to dereference stores or eventhooks in teardown - and in turn, assert stores gets loaded etc in the setup.
If you wish to use templates, then base your views on the dijit._TemplatedMixin
edit
Here is a simplified clarification of my oocms setup, where instead of basing it on BorderLayout, i will make it ContentPanes:
Example JSON for the menu, with a single item representing the above declared view
{
identifier: 'view',
label: 'name',
items: [
{ name: 'myForm', view: 'App.view.MyForm', extraParams: { foo: 'bar' } }
]
}
Base Application Controller in file 'AppPackagePath/Application.js'
Note, the code has not been tested but should give a good impression of how such a setup can be implemented
define(['dojo/_base/declare',
"dojo/_base/lang",
"dijit/registry",
"OoCmS/messagebus", // dependency mixin which will monitor 'notify/progress' topics'
"dojo/topic",
"dojo/data/ItemFileReadStore",
"dijit/tree/ForestStoreModel",
"dijit/Tree"
], function(declare, lang, registry, msgbus, dtopic, itemfilereadstore, djforestmodel, djtree) {
return declare("App.Application", [msgbus], {
paneContainer: NULL,
treeContainer: NULL,
menuStoreUrl: '/path/to/url-list',
_widgetInUse: undefined,
defaultPaneProps: {},
loading: false, // ismple mutex
constructor: function(args) {
lang.mixin(this, args);
if(!this.treeContainer || !this.paneContainer) {
console.error("Dont know where to place components")
}
this.defaultPaneProps = {
id: 'mainContentPane'
}
this.buildRendering();
},
buildRendering: function() {
this.menustore = new itemfilereadstore({
id: 'appMenuStore',
url:this.menuStoreUrl
});
this.menumodel = new djforestmodel({
id: 'appMenuModel',
store: this.menustore
});
this.menu = new djtree( {
model: this.menumodel,
showRoot: false,
autoExpand: true,
onClick: lang.hitch(this, this.paneRequested) // passes the item
})
// NEEDS a construct ID HERE
this.menu.placeAt(this.treeContainer)
},
paneRequested: function(item) {
if(this.loading || !item) {
console.warn("No pane to load, give me a menustore item");
return false;
}
if(!this._widgetInUse || !this._widgetInUse.isDirty()) {
dtopic.publish("notify/progress/loading");
this.loading = true;
}
if(typeof this._widgetInUse != "undefined") {
if(!this._widgetInUse.unload()) {
// bail out if widget says 'no' (isDirty)
return false;
}
this._widgetInUse.destroyRecursive();
delete this._widgetInUse;
}
var self = this,
modules = [this.menustore.getValue(item, 'view')];
require(modules, function(viewPane) {
self._widgetInUse = new viewPane(self.defaultProps);
// NEEDS a construct ID HERE
self._widgetInUse.placeAt(this.paneContainer)
self._widgetInUse.ready.then(function() {
self.paneLoaded();
})
});
return true;
},
paneLoaded: function() {
// hide ajax icons
dtopic.publish("notify/progress/done");
// assert widget has started
this._widgetInUse.startup();
this.loading = false;
}
})
})
AbstractView in file 'AppPackagePath/view/AbstractView.js':
define(["dojo/_base/declare",
"dojo/_base/Deferred",
"dojo/_base/lang",
"dijit/registry",
"dijit/layout/ContentPane"], function(declare, deferred, lang, registry, contentpane) {
return declare("App.view.AbstractView", [contentpane], {
observers: [], // all programmatic events handles should be stored for d/c on unload
parseOnLoad: false,
constructor: function(args) {
lang.mixin(this, args)
// setup ready.then resolve
this.ready = new deferred();
// once ready, create
this.ready.then(lang.hitch(this, this.postCreate));
// the above is actually not nescessary, since we could simply use onLoad in contentpane
if(typeof this.content != "undefined") {
this.set("content", this.content);
this.onLoad();
} else if(typeof 'href' == "undefined") {
console.warn("No contents nor href set in construct");
}
},
startup : function startup() {
this.inherited(arguments);
},
// if you override this, make sure to this.inherited(arguments);
onLoad: function() {
dojo.parser.parse(this.contentNode);
// alert the application, that loading is done
this.ready.resolve(null);
// and call render
this.render();
},
render: function() {
console.info('no custom rendering performed in ' + this.declaredClass)
},
isDirty: function() { return false; },
unload: function() {
dojo.forEach(this.observers, dojo.disconnect);
return true;
},
addObserver: function() {
// simple passthrough, adding the connect to handles
var handle = dojo.connect.call(dojo.window.get(dojo.doc),
arguments[0], arguments[1], arguments[2]);
this.observers.push(handle);
}
});
});
View implementation sample in file 'AppPackagePath/view/MyForm.js':
define(["dojo/_base/declare",
"dojo/_base/lang",
"App/view/AbstractView",
// the contentpane href will pull in some html
// in the html can be markup, which will be renderered when ready
// pull in requirements here
"dijit/form/Form", // markup require
"dijit/form/Button" // markup require
], function(declare, lang, baseinterface) {
return declare("App.view.MyForm", [baseinterface], {
// using an external HTML file
href: 'dojoform.html',
_isDirty : false,
isDirty: function() {
return this._isDirty;
},
render: function() {
var self = this;
this.formWidget = dijit.byId('embeddedForm') // hook up with loaded markup
// observer for children
dojo.forEach(this.formWidget._getDescendantFormWidgets(), function(widget){
if(! lang.isFunction(widget.onChange) )
console.log('unable to observe ' + widget.id);
self.addObserver(widget, 'onChange', function() {
self._isDirty = true;
});
});
//
},
// #override
unload: function() {
if(this.isDirty()) {
var go = confirm("Sure you wish to leave page before save?")
if(!go) return false;
}
return this.inherited(arguments);
}
})
});

Migrating from YUI2 to YUI3 and domready

I want to migrate the javascript in my site from YU2 to YUI3, but I am only a poor amateur programer and I am stuck at the first pitfall.
I have the following code:
MyApp.Core = function() {
return {
init: function(e, MyAppConfig) {
if (MyAppConfig.tabpanels) {
MyApp.Core.prepareTabpanels(MyAppConfig.tabpanels);
}
},
prepareTabpanels: function(tabpanels) {
// Code here
}
}
}();
var MyAppConfig = {
"tabpanels":{"ids":["navigation"]}
};
YAHOO.util.Event.addListener(window, "load", MyApp.Core.init, MyAppConfig);
How can I pass the MyAppConfig object to the MyApp.Core.init function by using YUI3 "domready" event listener?
Thanks in advance!
You should be able to do something like:
var MyApp = {};
MyApp.Core = function(){ return {
init: function(MyAppConfig) {
console.log(MyAppConfig);
},
prepareTabpanels: function(tabpanels) {
// Code here
}
}
}();
var MyAppConfig = {
"tabpanels":{"ids":["navigation"]}
};
YUI().use('node', 'event', function(Y){
Y.on('domready', MyApp.Core.init, this, MyAppConfig);
});
Note that the event is not passed in as the first parameter, it is the config.
Y.on accepts parameters as <event_type>, <callback_function>, <context>, <params>..
any parameter after the third item is passed through to the callback function so MyAppConfig becomes the first parameter in your init.
EDIT
See the YUI3 API documentation here: http://developer.yahoo.com/yui/3/api/YUI.html#method_on