I am having trouble understanding in what situations you would use custom events.
I mean the ones created by the CustomEvent constructor.
I understand the syntax itself, just not why it is useful. It would be nice if somebody could provide an example of real world application of custom events.
I use it (shameless plug) to raise "resize" events on div elements and then use a separate binding framework (aurelia) to listen to those events.
the explicit code example is:
var element = this.element; // some element
var erd = erd({ strategy: 'scroll' });
var widthOld = element.offsetWidth;
var heightOld = element.offsetHeight;
this.callback = () => {
var event = new CustomEvent("resize", {
detail: {
width: this.element.offsetWidth,
height: this.element.offsetHeight,
widthOld: widthOld,
heightOld: heightOld
}
});
element.dispatchEvent(event);
widthOld = this.element.offsetWidth;
heightOld = this.element.offsetHeight;
};
erd.listenTo(this.element, this.callback);
where erd is element-resize-detector that allows you to detect when any div changes shape.
Related
Really asking this to get a better understanding of object-oriented javascript and to uncover some best practices for this scenario. Let's say I have a javascript object, such as:
SideSlider = {
rightArrow: '.controls i.right',
dot: '.controls .dot',
slide: '.slide',
init: function() {
$(this.rightArrow).click(this.nextSlide.bind(this));
$(this.leftArrow).click(this.prevSlide.bind(this));
$(this.dot).click(this.dotClick.bind(this));
},
nextSlide: function() {
var activeSlide = $('.slide.active-slide'),
firstSlide = $(this.slide).first(),
lastSlide = $(this.slide).last(),
nextUp = activeSlide.next(),
activeDot = $(".active-dot"),
nextDot = activeDot.next();
activeSlide.removeClass("active-slide");
nextUp.addClass("active-slide");
activeDot.removeClass("active-dot");
nextDot.addClass("active-dot");
$(this.leftArrow).removeClass("inactive");
if ( lastSlide.hasClass("active-slide")) {
$(this.rightArrow).addClass("inactive");
}
}
}
What is the proper way to use this object on multiple instances of DOM modules? In other words, what is the 'best-practice' way of using this object's functionality on two 'slide' instances in the same DOM
You could create a constructor for your object, and then pass a container element to that constructor, so it will be acting on that DOM-slider only. Everywhere where you perform a jQuery selector to retrieve certain element(s), you should set the scope to the given container element. You can do this by providing that container as second argument to $(..., ...).
The object instances are created with new SideSlider(container). It could look something like this:
function SideSlider(container) {
// Perform the jQuery selections with the second argument
// so that the selection returns only elements within the container:
this.$rightArrow = $('.controls i.right', container);
this.$dot = $('.controls .dot', container);
this.$slide = $('.slide', container);
this.container = container;
// ... etc
// Perform init-logic immediately
this.$rightArrow.click(this.nextSlide.bind(this));
this.$leftArrow.click(this.prevSlide.bind(this));
this.$dot.click(this.dotClick.bind(this));
// ... etc
}
// Define methods on the prototype
SideSlider.prototype.nextSlide = function() {
var activeSlide = $('.slide.active-slide', this.container),
firstSlide = $(this.slide, this.container).first(),
lastSlide = $(this.slide, this.container).last(),
nextUp = activeSlide.next(),
activeDot = $(".active-dot", this.container),
nextDot = activeDot.next();
activeSlide.removeClass("active-slide");
nextUp.addClass("active-slide");
activeDot.removeClass("active-dot");
nextDot.addClass("active-dot");
$(this.leftArrow, this.container).removeClass("inactive");
if (lastSlide.hasClass("active-slide")) {
$(this.rightArrow, this.container).addClass("inactive");
}
// ... etc
};
// Create & use the two objects:
var slider1 = new SideSlider($('#slider1'));
var slider2 = new SideSlider($('#slider2'));
// ...
slider1.nextSlide();
// ...etc.
If you have ES6 support, use the class notation.
Seeing as it looks like you are using jQuery, I would recommend looking into turning your project into a jQuery plugin. This would allow you to assign your code per use, and it's used quite commonly by developers of sliders, and other sorts of JavaScript powered widgets. The jQuery website has a great tutorial on how to accomplish this, and it can be found here:
https://learn.jquery.com/plugins/basic-plugin-creation/
I'm looking for an event that tells me when a surface has been rendered so I can call methods like surface.focus().
If I call focus immediately after I create the surface it doesn't work. If I call it in a timer after some arbitrary time I expect it to be rendered, it works. So there must be an event I can use.
For example if I create a widget that builds a bunch of surfaces inside a view, how do I know when that widget has been fully built and more importantly, when is it being rendered so I can set focus on an input surface?
Thanks
I marked johntraver's response as the answer, but I also wanted to include a complete working example for the InputSurface for people like me just learning famous. This code subclasses InputSurface so that the focus method will work.
Once the InputSurface is rendered it gains focus.
TextBox.js
define(function(require, exports, module) {
var InputSurface = require('famous/surfaces/InputSurface');
var EventHandler = require('famous/core/EventHandler');
function TextBox(options) {
InputSurface.apply(this, arguments);
this._superDeploy = InputSurface.prototype.deploy;
}
TextBox.prototype = Object.create(InputSurface.prototype);
TextBox.prototype.constructor = TextBox;
TextBox.prototype.deploy = function deploy(target) {
this.eventHandler.trigger('surface-has-rendered', this);
this._superDeploy(target);
};
module.exports = TextBox;
});
implementation
this.email = new TextBox({
size: [300, 40],
placeholder:'email'
});
var event_handler = new EventHandler();
event_handler.on('surface-has-rendered', function(control){
control.focus();
});
this.email.pipe(event_handler);
This is another case of when subclassing may be your easiest and most straight forward approach. In this example, Surface is subclassed and I am sure to grab the deploy function of the Surface and bind it to the MySurface instance for later use. Then when we override deploy later on, we can call super for the surface and not have to worry about altering core code. eventHandler is a property built into Surface, so that is used to send the render event.
An interesting test happened while making this example. If you refresh the code, and grunt pushes the changes to an unopened tab.. You event will not be fired until you open the tab again. Makes sense, but it was nice to see!
Here is what I did..
Good Luck!
var Engine = require('famous/core/Engine');
var Surface = require('famous/core/Surface');
var StateModifier = require('famous/modifiers/StateModifier');
var EventHandler = require('famous/core/EventHandler')
function MySurface(options) {
Surface.apply(this, arguments);
this._superDeploy = Surface.prototype.deploy
}
MySurface.prototype = Object.create(Surface.prototype);
MySurface.prototype.constructor = MySurface;
MySurface.prototype.elementType = 'div';
MySurface.prototype.elementClass = 'famous-surface';
MySurface.prototype.deploy = function deploy(target) {
this._superDeploy(target);
this.eventHandler.trigger('surface-has-rendered', this);
};
var context = Engine.createContext();
var event_handler = new EventHandler();
event_handler.on('surface-has-rendered', function(data){
console.log("Hello Render!");
console.log(data);
})
var surface = new MySurface({
size: [200,200],
content: "Hello",
properties: {
color: 'white',
textAlign: 'center',
lineHeight: '200px',
backgroundColor: 'green'
}
});
surface.pipe(event_handler);
context.add(new StateModifier({origin:[0.5,0.5]})).add(surface);
I know this has been answered already, all be it a few months ago. I just thought that I would add that currently you can do this without subclassing as follows:
var textbox = new InputSurface({
size: [true,true],
placeholder: 'Text'
});
textbox.on('deploy', function() {
textbox.focus();
});
Is there any way to catch the document.createElement() event?
For example, somewhere, inside the <body> section I have
<script>
var div = document.createElement("div");
<script>
Is it possible to track that event from the <head> section (using some addEventListener, mutation observer, or any other way)?
Note: I need to track the creation of the element, not the insertion
Warning This code won't work in every browser. All bets are off when it comes to IE.
(function() {
// Step1: Save a reference to old createElement so we can call it later.
var oldCreate = document.createElement;
// Step 2: Create a new function that intercepts the createElement call
// and logs it. You can do whatever else you need to do.
var create = function(type) {
console.log("Creating: " + type);
return oldCreate.call(document, type);
}
// Step 3: Replace document.createElement with our custom call.
document.createElement = create;
}());
This is, similarly to other answers, an imperfect and incomplete solution (and is explicitly tested in only Chrome 34 on Windows 8.1):
// creating a function to act as a wrapper to document.createElement:
document.create = function(elType){
// creating the new element:
var elem = document.createElement(elType),
// creating a custom event (called 'elementCreated'):
evt = new CustomEvent('elementCreated', {
// details of the custom event:
'detail' : {
// what was created:
'elementType' : elem.tagName,
// a reference to the created node:
'elementNode' : elem
}
});
// dispatching the event:
this.dispatchEvent(evt);
// returning the created element:
return elem;
};
// assigning an event-handler to listen for the 'elementCreated' event:
document.addEventListener('elementCreated', function(e){
// react as you like to the creation of a new element (using 'document.create()'):
console.log(e);
});
// creating a new element using the above function:
var newDiv = document.create('div');
JS Fiddle demo.
References:
Creating and triggering events (MDN).
EventTarget.addEventListener().
EventTarget.dispatchEvent().
It's possible to create custom Events in javascript. And it's supported by all browsers too.
Check it out: http://jsfiddle.net/JZwB4/1/
document.createElement = (function(){
var orig = document.createElement;
var event = new CustomEvent("elemCreated");
return function() {
document.body.dispatchEvent(event);
orig.call(document,x);
};
})();
document.body.addEventListener('elemCreated', function(){
console.log('created');
},false);
var x= document.createElement('p'); //"created" in console
Let's say I have a setup like this.
var Account = function(data) {
this.data = data;
this.domElement = (function(){ code that generates DOM element that will represent this account })();
this.domElement.objectReference = this;
}
Account.prototype = {
show: function() { this.domElement.classList.remove('hidden'); },
hide: function() { this.domElement.classList.add('hidden') }
}
My question is about the last line: this.domElement.objectReference = this;
It would be a useful thing to have because then I can add event listeners to my DOM element and still get access to the object itself. I can add methods that would affect my DOM element, such as hide() and show(), for instance, without having to resort to modifying visibility of the DOM element using CSS directly.
I tested this code and it works like I want it to, but I'm curious whether this would cause memory leaks or some other unpleasantness or if it's an acceptable thing to do?
Thank you!
Luka
I know this has been answered by #PaulS. already, but I find the answer counter intuitive (returning a DOM element from the Account constructor is not expected) and too DOM-centric, but at the same time the implementation is very simple, so I am not sure what to think ;)
Anyway, I just wanted to show a different way of doing it. You can store Account instances in a map and give them a unique id (perhaps they have one already), then you store that id as a data attribute on the DOM element. Finally you implement a getById function or something similar to retrieve the account instance by id from the listeners.
That's pretty much how jQuery's data works.
Here's an example with delegated events like you wanted from the comments.
DEMO
var Account = (function (accounts, id) {
function Account(data) {
accounts[this._id = ++id] = this;
this.el = createEl.call(this);
}
Account.prototype = {
constructor: Account,
show: function() { this.el.classList.remove('hidden'); },
hide: function() { this.el.classList.add('hidden'); }
};
function createEl() {
var el = this.el = document.createElement('div');
el.className = 'account';
el.innerHTML = el.dataset.accountId = this._id;
return el;
}
Account.getById = function (id) {
return accounts[id];
};
Account.init = function () {
//add delegate listeners
document.addEventListener('click', function (e) {
var target = e.target,
account = Account.getById(target.dataset.accountId);
if (!account) return;
account.hide();
});
};
return Account;
})({}, 0);
//once DOM loaded
Account.init(); //start listening to events
var body = document.body;
body.appendChild(new Account().el);
body.appendChild(new Account().el);
Why not have domElement as a variable, and return it from your function? To keep the reference to your constructed Object (but only where this is as expected), you could do a if (this instanceof Account) domElement.objectReference = this;
You've now saved yourself from circular references and can access both the Node and the Object. Doing it this way around is more helpful if you're expecting to lose the direct reference to your Account instance, but expect to need it when "looking up" the Node it relates to at some later time.
Code as requested
var Account = function (data) {
var domElement; // var it
this.data = data;
domElement = (function(){/* ... */}()); // use var
if (this instanceof Account)
domElement.objectReference = this; // assign `this`
return domElement;
};
// prototype as before
Returned element is now the Node, not the Object; so you'd access the Account instance like this
var domElement = new Account();
domElement.objectReference.show(); // for example
In my opinion there is nothing good about referencing the object inside of the object itself. The main reason for this is complexity and obscurity.
If you would point out how exactly are you using this domElement.objectReference later in the code, I am sure that I or someone else would be able to provide a solution without this reference.
I'm working on a fiddly web interface which is mostly built with JavaScript. Its basically one (very) large form with many sections. Each section is built based on options from other parts of the form. Whenever those options change the new values are noted in a "registry" type object and the other sections re-populate accordingly.
Having event listeners on the many form fields is starting to slow things down, and refreshing the whole form for each change would be too heavy/slow for the user.
I'm wondering whether its possible to add listeners to the registry object's attributes rather than the form elements to speed things up a bit? And, if so, could you provide/point me to some sample code?
Further information:
This is a plug-in for jQuery, so any functionality I can build-on from that library would be helpful but not essential.
Our users are using IE6/7, Safari and FF2/3, so if it is possible but only for "modern" browsers I'll have to find a different solution.
As far as I know, there are no events fired on Object attribute changes (edit: except, apparently, for Object.watch).
Why not use event delegation wherever possible? That is, events on the form rather than on individual form elements, capturing events as they bubble up?
For instance (my jQuery is rusty, forgive me for using Prototype instead, but I'm sure you'll be able to adapt it easily):
$(form).observe('change', function(e) {
// To identify changed field, in Proto use e.element()
// but I think in jQuery it's e.target (as it should be)
});
You can also capture input and keyup and paste events if you want it to fire on text fields before they lose focus. My solution for this is usually:
Gecko/Webkit-based browsers: observe input on the form.
Also in Webkit-based browsers: observe keyup and paste events on textareas (they do not fire input on textareas for some reason).
IE: observe keyup and paste on the form
Observe change on the form (this fires on selects).
For keyup and paste events, compare a field's current value against its default (what its value was when the page was loaded) by comparing a text field's value to its defaultValue
Edit: Here's example code I developed for preventing unmodified form submission and the like:
What is the best way to track changes in a form via javascript?
Thanks for the comments guys. I've gone with the following:
var EntriesRegistry = (function(){
var instance = null;
function __constructor() {
var
self = this,
observations = {};
this.set = function(n,v)
{
self[n] = v;
if( observations[n] )
for( var i=0; i < observations[n].length; i++ )
observations[n][i].apply(null, [v, n]);
}
this.get = function(n)
{
return self[n];
}
this.observe = function(n,f)
{
if(observations[n] == undefined)
observations[n] = [];
observations[n].push(f);
}
}
return new function(){
this.getInstance = function(){
if (instance == null)
{
instance = new __constructor();
instance.constructor = null;
}
return instance;
}
}
})();
var entries = EntriesRegistry.getInstance();
var test = function(v){ alert(v); };
entries.set('bob', 'meh');
entries.get('bob');
entries.observe('seth', test);
entries.set('seth', 'dave');
Taking on-board your comments, I'll be using event delegation on the form objects to update the registry and trigger the registered observing methods.
This is working well for me so far... can you guys see any problems with this?
You could attach a listener to a container (the body or the form) and then use the event parameter to react to the change. You get all the listener goodness but only have to attach one for the container instead of one for every element.
$('body').change(function(event){
/* do whatever you want with event.target here */
console.debug(event.target); /* assuming firebug */
});
The event.target holds the element that was clicked on.
SitePoint has a nice explanation here of event delegation:
JavaScript event delegation is a simple technique by which you add a single event handler to a parent element in order to avoid having to add event handlers to multiple child elements.
Mozilla-engined browsers support Object.watch, but I'm not aware of a cross-browser compatible equivalent.
Have you profiled the page with Firebug to get an idea of exactly what's causing the slowness, or is "lots of event handlers" a guess?
Small modification to the previous answer : by moving the observable code to an object, one can make an abstraction out of it and use it to extend other objects with jQuery's extend method.
ObservableProperties = {
events : {},
on : function(type, f)
{
if(!this.events[type]) this.events[type] = [];
this.events[type].push({
action: f,
type: type,
target: this
});
},
trigger : function(type)
{
if (this.events[type]!==undefined)
{
for(var e = 0, imax = this.events[type].length ; e < imax ; ++e)
{
this.events[type][e].action(this.events[type][e]);
}
}
},
removeEventListener : function(type, f)
{
if(this.events[type])
{
for(var e = 0, imax = this.events[type].length ; e < imax ; ++e)
{
if(this.events[type][e].action == f)
this.events[type].splice(e, 1);
}
}
}
};
Object.freeze(ObservableProperties);
var SomeBusinessObject = function (){
self = $.extend(true,{},ObservableProperties);
self.someAttr = 1000
self.someMethod = function(){
// some code
}
return self;
}
See the fiddle : https://jsfiddle.net/v2mcwpw7/3/
jQuery is just amazing. Although you could take a look to ASP.NET AJAX Preview.
Some features are just .js files, no dependency with .NET. May be you could find usefull the observer pattern implementation.
var o = { foo: "Change this string" };
Sys.Observer.observe(o);
o.add_propertyChanged(function(sender, args) {
var name = args.get_propertyName();
alert("Property '" + name + "' was changed to '" + sender[name] + "'.");
});
o.setValue("foo", "New string value.");
Also, Client Side templates are ready to use for some interesting scenarios.
A final note, this is fully compatible with jQuery (not problem with $)
Links: Home page, Version I currently use
I was searching for the same thing and hitted your question... none of the answers satisfied my needs so I came up with this solution that I would like to share:
var ObservedObject = function(){
this.customAttribute = 0
this.events = {}
// your code...
}
ObservedObject.prototype.changeAttribute = function(v){
this.customAttribute = v
// your code...
this.dispatchEvent('myEvent')
}
ObservedObject.prototype.addEventListener = function(type, f){
if(!this.events[type]) this.events[type] = []
this.events[type].push({
action: f,
type: type,
target: this
})
}
ObservedObject.prototype.dispatchEvent = function(type){
for(var e = 0; e < this.events[type].length; ++e){
this.events[type][e].action(this.events[type][e])
}
}
ObservedObject.prototype.removeEventListener = function(type, f){
if(this.events[type]) {
for(var e = 0; e < this.events[type].length; ++e){
if(this.events[type][e].action == f)
this.events[type].splice(e, 1)
}
}
}
var myObj = new ObservedObject()
myObj.addEventListener('myEvent', function(e){// your code...})
It's a simplification of the DOM Events API and works just fine!
Here is a more complete example