The following is a snippet from the Backbone.js annotated source code:
var eventsApi = function(iteratee, events, name, callback, opts) {
var i = 0, names;
if (name && typeof name === 'object') {
if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback;
for (names = _.key(names); i < names.length; i++) {
events = eventsApi(iteratee, events, names[i], name[names[i]], opts);
}
} else if (name && eventSplitter.test(name)) {
for (names = name.split(eventSplitter); i < names.length; i++) {
events = iteratee(events, names[i], callback, opts);
}
} else {
events = iteratee(events, name, callback, opts);
}
return events;
};
The eventsApi function checks for events as objects, in order to handle jQuery-style event maps.
But why does it call eventsApi recursively as it iterates through all the events?
The iteratee in the above is the following:
var onApi = function(events, name, callback, options) {
if (callback) {
var handlers = events[name] || (events[name] = []);
var context = options.context, ctx = options.ctx, listening = options.listening;
if (listening) listening.count++;
handlers.push({callback: callback, context: context, ctx: context || ctx, listening: listening});
}
return events;
};
it registers an event for single attribute (name).
eventsApi checks if the second parameter is an object, in that case it calls itself to register events for all the properties of the object, for example the attributes object of a model. This is a common use of recursion.
Related
I want to crate javascript object that accepts setting and provide multiple events with single addListener function. for example addListener({success: callback,fail:callback}) etc. I hope my requirement is clear.
var myCustomObject=new MyCustomeObject({name:'anu', age:'30'});
myCustomObject.addListener({
success: function(e){ console.log(e)},
fail: function(ef){ console.log(ef)}
});
You can implement your own EventEmitter like this:
const EventEmitter = function () {
this.events = {};
};
Then you need to create function for subscribe:
EventEmitter.prototype.on = function (event, listener) {
if (typeof this.events[event] !== 'object') {
this.events[event] = [];
}
this.events[event].push(listener);
};
and of course function for emit:
EventEmitter.prototype.emit = function (event) {
let i, listeners, length, args = [].slice.call(arguments, 1);
if (typeof this.events[event] === 'object') {
listeners = this.events[event].slice();
length = listeners.length;
for (i = 0; i < length; i++) {
listeners[i].apply(this, args);
}
}
};
new Event does not work in IE11, and unfortunately neither does the polyfill from MDN and this question: Internet Explorer 9, 10 & 11 Event constructor doesn't work, since they rely on document.createEvent.
Are there any workarounds for creating custom events in the worker context?
Use a method which aliases an implementation of an existing event system. For example:
sinon.Event = function Event(type, bubbles, cancelable, target) {
this.initEvent(type, bubbles, cancelable, target);
};
sinon.Event.prototype = {
initEvent: function (type, bubbles, cancelable, target) {
this.type = type;
this.bubbles = bubbles;
this.cancelable = cancelable;
this.target = target;
},
stopPropagation: function () {},
preventDefault: function () {
this.defaultPrevented = true;
}
};
sinon.CustomEvent = function CustomEvent(type, customData, target) {
this.initEvent(type, false, false, target);
this.detail = customData.detail || null;
};
sinon.CustomEvent.prototype = new sinon.Event();
sinon.CustomEvent.prototype.constructor = sinon.CustomEvent;
sinon.EventTarget = {
addEventListener: function addEventListener(event, listener) {
this.eventListeners = this.eventListeners || {};
this.eventListeners[event] = this.eventListeners[event] || [];
push.call(this.eventListeners[event], listener);
},
removeEventListener: function removeEventListener(event, listener) {
var listeners = this.eventListeners && this.eventListeners[event] || [];
for (var i = 0, l = listeners.length; i < l; ++i) {
if (listeners[i] === listener) {
return listeners.splice(i, 1);
}
}
},
dispatchEvent: function dispatchEvent(event) {
var type = event.type;
var listeners = this.eventListeners && this.eventListeners[type] || [];
for (var i = 0; i < listeners.length; i++) {
if (typeof listeners[i] === "function") {
listeners[i].call(this, event);
} else {
listeners[i].handleEvent(event);
}
}
return !!event.defaultPrevented;
}
};
}
/**
* Used to bind event listeners to the worker. Internally it uses the jQuery `.on` method.
* #method on
* #param {Mixed} args* Lookup the jQuery `.on` API for argument list.
* #chainable
*/
var worker = new WebWorker('./worker-script.js');
worker.on('my-custom-event', function () {
console.log('custom event triggered!');
});
References
jQuery github repo: sinon.js
web-worker/web-worker.js at master · tanzeelkazi/web-worker
Improving Web Worker usage in PWA's (and an implementation in PureScript)
peter.michaux.ca - Anonymous Events - Extremely Loose Coupling
John Resig - Flexible Javascript Events
... and the winner is ... - QuirksBlog
I have been trying for days upon weeks with trying to build a personal library without jQuery for my school club, and so far I am hitting a rut when it comes to passing through an element or objects through to another function. The notation I am trying for is this :
CC(function(){
CC('id:wrapper').set('html','Hello World!');
});
That is my test code, and the library looks as it does below:
"use strict";
var CC = function () {
var args = arguments[0] || {};
if(typeof args === "object") {
args = args || {};
}
else if(typeof args === "function") {
args = arguments[0];
return window.onload = args;
}
else if(typeof args !== "object" || typeof args !== "function") {
var elem = get(args);
return elem;
}
};
CC({
//Can only be done once. Will return TypeError because '$' won't exist afterward
noConflict : function (name) {
name = new CC();
return name;
}
});
//The way to modify things
CC.mod = CC.prototype = {};
CC.extend = CC.mod.extend = function () {
var args = arguments[0] || {};
var target = get(args);
return target;
};
CC.mod.extend({
//Use psuedo types to set specific values (required)
set : function(type, value) {
return set(this.target, type, value);
}
});
//General get function to get selectors, generate functions, or return values
function get() {
var args = arguments[0] || {};
//Check if the argument is a function
//If it is, return the function on page load
if (typeof args === "function") {
return window.onload = args;
}
//Check argument type
if(typeof args !== "object") {
args = arguments[0];
return args;
}
else {
args = {};
return args;
}
//Check if args has an elem psuedo
if(args.indexOf("id:") > -1 || args.indexOf("class:") > -1 || args.indexOf("tag:") > -1) {
var target = args;
//Run id psuedo
if(target.indexOf("id:") > -1) {
target = target.replace('id:','');
console.log(target);
return document.getElementById(target);
}
//Run class psuedo
else if(target.indexOf("class:") > -1) {
target = target.replace('class:','');
console.log(target);
return document.getElementsByClassName(target);
}
//Run tag psuedo
else if(target.indexOf("tag:") > -1) {
target = target.replace('class:','');
console.log(target);
return document.getElementsByTagName(target);
}
}
//Check if args is not null
//If not, then return args value
if(args !== null) {
return args.value;
}
else {
return null;
}
}
//General function to set things for elements
function set(elem, property, value) {
//If the element provided is part of getting an element
//If it is, run the psuedo checker
if(elem.indexOf("id:") > -1 || elem.indexOf("class:") > -1 || elem.indexOf("tag:") > -1) {
elem = get(elem);
//Rerun the set() function to set properties and values
set(elem, property, value);
}
//If not, then run the type psuedo checker
else {
//Check if style
if(property.indexOf("css:") > -1 || property.indexOf("style:") > -1) {
//Check for the independent types
if(property.indexOf("css:") > -1) {
property = property.replace('css:','');
return elem.style[property] = value;
}
else if(property.indexOf("style:") > -1) {
property = property.replace('style:','');
return elem.style[property] = value;
}
}
//Check if attribute
else if(property.indexOf("attr:") > -1) {
property = property.replace('attr:','');
return elem.setAttribute(property, value);
}
//Check if html
else if(property.indexOf("html") > -1) {
return elem.innerHTML = value;
}
//To add more, just add another else if(condition...) {Code} statement
//Condition must be defined in psuedo selectors
//Condition must be property.indexOf("selector:" > -1)
//return statement must consist of a return value from the value parameter
}
}
I don't know how to get my methods to pass through correctly and I don't know how to get my methods to apply to the element in the CC('id:wrapper') code. I already have the 'psuedo selector' made to get rid of the id: code. Any help would be much appreciated!
You've posted quite some code which I wasn't able to get to work quickly, so I'm not sure if this will help you out.
The basic idea is that your CC method will always have to return an object with a set method. If there's no element with id="wrapper", you'll have to figure out a way to handle exceptions.
You can use bind to create a new function from an earlier defined function with a pre-bound this context and pre-filled in arguments.
A simplified example:
var CC = function(query) {
return {
set: set.bind(null, document.querySelector(query))
};
}
function set(element, attr, val) {
element.setAttribute(attr, val);
}
CC("input").set("placeholder", "I was set by js");
<input type="text" />
If you want to do more advanced binding of arguments, I'd suggest you google "Currying". With some code, you can make functions automatically return new functions when called with less arguments than needed.
What .bind does:
The bind method is defined in Function.prototype. You can call it on any function you've defined to create a new function.
The first argument that goes in to bind, is used as the this context in the newly created function. You could, for example, do:
var myDiv = document.querySelector("div");
var logText = function() {
console.log(this.innerText);
};
var logDivText = logText.bind(myDiv);
logText(); // Bound to window, logs undefined
logDivText(); // Bound to div, logs text
<div>Text in a div</div>
Any other arguments passed to bind, are automatically passed as arguments. For example:
var sum = function(a, b) {
return a + b;
};
var sum3 = sum.bind(null, 3); // we don't use this, so we don't define it
console.log(sum3(5)); // Prints 8
I'm using all of the latest dependencies for emberjs and yet I end up with an error on initializing the scripts in the page at ember-data-latest.min.js with:
Uncaught TypeError: Object function () {...} has no method 'registerInjection'
Before even writing a single line for my app. Why is that?
Appreciate any kind help.
Here's my script list:
jquery-1.10.2.min.js
handlebars-v1.3.0.js
ember-1.5.1.js
ember-states.js
ember-data-latest.min.js
And here's the full error:
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, nullDescriptor);
o_defineProperty(this, '__nextSuper', undefinedDescriptor);
var m = meta(this), proto = m.proto;
m.proto = this;
if (initMixins) {
// capture locally so we can clear the closed over variable
var mixins = initMixins;
initMixins = null;
this.reopen.apply(this, mixins);
}
if (initProperties) {
// capture locally so we can clear the closed over variable
var props = initProperties;
initProperties = null;
var concatenatedProperties = this.concatenatedProperties;
for (var i = 0, l = props.length; i < l; i++) {
var properties = props[i];
Ember.assert("Ember.Object.create no longer supports mixing in other definitions, use createWithMixins instead.", !(properties instanceof Ember.Mixin));
if (typeof properties !== 'object' && properties !== undefined) {
throw new Ember.Error("Ember.Object.create only accepts objects.");
}
if (!properties) { continue; }
var keyNames = Ember.keys(properties);
for (var j = 0, ll = keyNames.length; j < ll; j++) {
var keyName = keyNames[j];
if (!properties.hasOwnProperty(keyName)) { continue; }
var value = properties[keyName],
IS_BINDING = Ember.IS_BINDING;
if (IS_BINDING.test(keyName)) {
var bindings = m.bindings;
if (!bindings) {
bindings = m.bindings = {};
} else if (!m.hasOwnProperty('bindings')) {
bindings = m.bindings = o_create(m.bindings);
}
bindings[keyName] = value;
}
var desc = m.descs[keyName];
Ember.assert("Ember.Object.create no longer supports defining computed properties. Define computed properties using extend() or reopen() before calling create().", !(value instanceof Ember.ComputedProperty));
Ember.assert("Ember.Object.create no longer supports defining methods that call _super.", !(typeof value === 'function' && value.toString().indexOf('._super') !== -1));
Ember.assert("`actions` must be provided at extend time, not at create " +
"time, when Ember.ActionHandler is used (i.e. views, " +
"controllers & routes).", !((keyName === 'actions') && Ember.ActionHandler.detect(this)));
if (concatenatedProperties && indexOf(concatenatedProperties, keyName) >= 0) {
var baseValue = this[keyName];
if (baseValue) {
if ('function' === typeof baseValue.concat) {
value = baseValue.concat(value);
} else {
value = Ember.makeArray(baseValue).concat(value);
}
} else {
value = Ember.makeArray(value);
}
}
if (desc) {
desc.set(this, keyName, value);
} else {
if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) {
this.setUnknownProperty(keyName, value);
} else if (MANDATORY_SETTER) {
Ember.defineProperty(this, keyName, null, value); // setup mandatory setter
} else {
this[keyName] = value;
}
}
}
}
}
finishPartial(this, m);
this.init.apply(this, arguments);
m.proto = proto;
finishChains(this);
sendEvent(this, "init");
} has no method 'registerInjection'
You need to make sure to use the latest version which gets published at Ember build site.
The latest build for Ember Data is found here.
Is it possible to simply add event listeners to certain elements to detect if their height or width have been modified? I'd like do this without using something intensive like:
$(window).resize(function() { ... });
Ideally, I'd like to bind to specific elements:
$("#primaryContent p").resize(function() { ... });
It seems like using a resize handler on the window is the only solution, but this feels like overkill. It also doesn't account for situations where an element's dimensions are modified programatically.
I just came up with a purely event-based way to detect element resize for any element that can contain children, I've pasted the code from the solution below.
See also the original blog post, which has some historical details. Previous versions of this answer were based on a previous version of the blog post.
The following is the JavaScript you’ll need to enable resize event listening.
(function(){
var attachEvent = document.attachEvent;
var isIE = navigator.userAgent.match(/Trident/);
var requestFrame = (function(){
var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
function(fn){ return window.setTimeout(fn, 20); };
return function(fn){ return raf(fn); };
})();
var cancelFrame = (function(){
var cancel = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame ||
window.clearTimeout;
return function(id){ return cancel(id); };
})();
function resizeListener(e){
var win = e.target || e.srcElement;
if (win.__resizeRAF__) cancelFrame(win.__resizeRAF__);
win.__resizeRAF__ = requestFrame(function(){
var trigger = win.__resizeTrigger__;
trigger.__resizeListeners__.forEach(function(fn){
fn.call(trigger, e);
});
});
}
function objectLoad(e){
this.contentDocument.defaultView.__resizeTrigger__ = this.__resizeElement__;
this.contentDocument.defaultView.addEventListener('resize', resizeListener);
}
window.addResizeListener = function(element, fn){
if (!element.__resizeListeners__) {
element.__resizeListeners__ = [];
if (attachEvent) {
element.__resizeTrigger__ = element;
element.attachEvent('onresize', resizeListener);
}
else {
if (getComputedStyle(element).position == 'static') element.style.position = 'relative';
var obj = element.__resizeTrigger__ = document.createElement('object');
obj.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;');
obj.__resizeElement__ = element;
obj.onload = objectLoad;
obj.type = 'text/html';
if (isIE) element.appendChild(obj);
obj.data = 'about:blank';
if (!isIE) element.appendChild(obj);
}
}
element.__resizeListeners__.push(fn);
};
window.removeResizeListener = function(element, fn){
element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1);
if (!element.__resizeListeners__.length) {
if (attachEvent) element.detachEvent('onresize', resizeListener);
else {
element.__resizeTrigger__.contentDocument.defaultView.removeEventListener('resize', resizeListener);
element.__resizeTrigger__ = !element.removeChild(element.__resizeTrigger__);
}
}
}
})();
Usage
Here’s a pseudo code usage of this solution:
var myElement = document.getElementById('my_element'),
myResizeFn = function(){
/* do something on resize */
};
addResizeListener(myElement, myResizeFn);
removeResizeListener(myElement, myResizeFn);
Demo
http://www.backalleycoder.com/resize-demo.html
Here is a jQuery plugin with watch and unwatch methods that can watch particular properties of an element. It is invoked as a method of a jQuery object. It uses built-in functionality in browsers that return events when the DOM changes, and uses setTimeout() for browsers that do not support these events.
The general syntax of the watch function is below:
$("selector here").watch(props, func, interval, id);
props is a comma-separated string of the properties you wish to
watch (such as "width,height").
func is a callback function, passed the parameters watchData, index, where watchData refers to an object of the form { id: itId, props: [], func: func, vals: [] }, and index is the index of the changed property. this refers to the changed element.
interval is the interval, in milliseconds, for setInterval() in browsers that do not support property watching in the DOM.
id is an optional id that identifies this watcher, and is used to remove a particular watcher from a jQuery object.
The general syntax of the unwatch function is below:
$("selector here").unwatch(id);
id is an optional id that identifies this watcher to be removed. If id is not specified, all watchers from the object will be removed.
For those who are curious, the code of the plugin is reproduced below:
$.fn.watch = function(props, func, interval, id) {
/// <summary>
/// Allows you to monitor changes in a specific
/// CSS property of an element by polling the value.
/// when the value changes a function is called.
/// The function called is called in the context
/// of the selected element (ie. this)
/// </summary>
/// <param name="prop" type="String">CSS Property to watch. If not specified (null) code is called on interval</param>
/// <param name="func" type="Function">
/// Function called when the value has changed.
/// </param>
/// <param name="func" type="Function">
/// optional id that identifies this watch instance. Use if
/// if you have multiple properties you're watching.
/// </param>
/// <param name="id" type="String">A unique ID that identifies this watch instance on this element</param>
/// <returns type="jQuery" />
if (!interval)
interval = 200;
if (!id)
id = "_watcher";
return this.each(function() {
var _t = this;
var el = $(this);
var fnc = function() { __watcher.call(_t, id) };
var itId = null;
if (typeof (this.onpropertychange) == "object")
el.bind("propertychange." + id, fnc);
else if ($.browser.mozilla)
el.bind("DOMAttrModified." + id, fnc);
else
itId = setInterval(fnc, interval);
var data = { id: itId,
props: props.split(","),
func: func,
vals: []
};
$.each(data.props, function(i) { data.vals[i] = el.css(data.props[i]); });
el.data(id, data);
});
function __watcher(id) {
var el = $(this);
var w = el.data(id);
var changed = false;
var i = 0;
for (i; i < w.props.length; i++) {
var newVal = el.css(w.props[i]);
if (w.vals[i] != newVal) {
w.vals[i] = newVal;
changed = true;
break;
}
}
if (changed && w.func) {
var _t = this;
w.func.call(_t, w, i)
}
}
}
$.fn.unwatch = function(id) {
this.each(function() {
var w = $(this).data(id);
var el = $(this);
el.removeData();
if (typeof (this.onpropertychange) == "object")
el.unbind("propertychange." + id, fnc);
else if ($.browser.mozilla)
el.unbind("DOMAttrModified." + id, fnc);
else
clearInterval(w.id);
});
return this;
}
Yes it is possible. You will have to track all of the elements on load and store it. You can try out the demo here. In it, you don't have to use any libraries, but I used jQuery just to be faster.
First thing first - Store their initial size
You can do that by using this method:
var state = []; //Create an public (not necessary) array to store sizes.
$(window).load(function() {
$("*").each(function() {
var arr = [];
arr[0] = this
arr[1] = this.offsetWidth;
arr[2] = this.offsetHeight;
state[state.length] = arr; //Store all elements' initial size
});
});
Again, I used jQuery just to be fast.
Second - Check!
Of course you will need to check if it has been changed:
function checksize(ele) {
for (var i = 0; i < state.length; i++) { //Search through your "database"
if (state[i][0] == ele) {
if (state[i][1] == ele.offsetWidth && state[i][2] == ele.offsetHeight) {
return false
} else {
return true
}
}
}
}
Simply it will return false if it has not been change, true if it has been change.
Hope this helps you out!
Demo: http://jsfiddle.net/DerekL/6Evk6/