Rectangle 27 2564

Issues with change listeners:

AngularJS remembers the value and compares it to a previous value. This is basic dirty-checking. If there is a change in value, then it fires the change event.

The $apply() method, which is what you call when you are transitioning from a non-AngularJS world into an AngularJS world, calls $digest(). A digest is just plain old dirty-checking. It works on all browsers and is totally predictable.

To contrast dirty-checking (AngularJS) vs change listeners (KnockoutJS and Backbone.js): While dirty-checking may seem simple, and even inefficient (I will address that later), it turns out that it is semantically correct all the time, while change listeners have lots of weird corner cases and need things like dependency tracking to make it more semantically correct. KnockoutJS dependency tracking is a clever feature for a problem which AngularJS does not have.

  • The syntax is atrocious, since browsers do not support it natively. Yes, there are proxies, but they are not semantically correct in all cases, and of course there are no proxies on old browsers. The bottom line is that dirty-checking allows you to do POJO, whereas KnockoutJS and Backbone.js force you to inherit from their classes, and access your data through accessors.
  • Change coalescence. Suppose you have an array of items. Say you want to add items into an array, as you are looping to add, each time you add you are firing events on change, which is rendering the UI. This is very bad for performance. What you want is to update the UI only once, at the end. The change events are too fine-grained.
  • Change listeners fire immediately on a setter, which is a problem, since the change listener can further change data, which fires more change events. This is bad since on your stack you may have several change events happening at once. Suppose you have two arrays which need to be kept in sync for whatever reason. You can only add to one or the other, but each time you add you fire a change event, which now has an inconsistent view of the world. This is a very similar problem to thread locking, which JavaScript avoids since each callback executes exclusively and to completion. Change events break this since setters can have far-reaching consequences which are not intended and non obvious, which creates the thread problem all over again. It turns out that what you want to do is to delay the listener execution, and guarantee, that only one listener runs at a time, hence any code is free to change data, and it knows that no other code runs while it is doing so.

So the real question is this: How many comparisons can you do on a browser in 50ms? This is a hard question to answer as many factors come into play, but here is a test case: http://jsperf.com/angularjs-digest/6 which creates 10,000 watchers. On a modern browser this takes just under 6ms. On InternetExplorer8 it takes about 40ms. As you can see, this is not an issue even on slow browsers these days. There is a caveat: The comparisons need to be simple to fit into the time limit... Unfortunately it is way too easy to add a slow comparison into AngularJS, so it is easy to build slow applications when you don't know what you are doing. But we hope to have an answer by providing an instrumentation module, which would show you which are the slow comparisons.

It turns out that video games and GPUs use the dirty-checking approach, specifically because it is consistent. As long as they get over the monitor refresh rate (typically 50-60 Hz, or every 16.6-20 ms), any performance over that is a waste, so you're better off drawing more stuff, than getting FPS higher.

@Mark - yes, in KO you just add .extend({ throttle: 500 }) to wait 500 milliseconds after the last change event before acting on it.

This entire answer is great other than "As long as they get 50 fps, any performance over that is a waste, since the human eye can not appreciate it, so you're better off drawing more stuff, than getting fps higher." That statement is completely incorrect depending on your application. The eye can definitely appreciate more than 50 fps, and as the various problems with VR show (read any of the latest from John Carmack or Michael Abrash, especially the latter's GDC 2013 VR talk), 50 fps is actually way too slow. Other than that, your answer is great. I just don't want misinformation spreading.

Just wondering, if your app is like Twitter or a comment thread/forum, and you implement infinite scrolling based on Angular, you could run into the "2000 pieces of info" "limit". A single comment could easily have several variables for the author's name, profile img, content, datetime, and etc. Also, say we have a giant array for storing all the comments/posts, every dirty checking would require scanning of this array, am I right? This would make the browser a bit laggy at times which is a bad user experience. What do you suggest we do in this case to ensure reasonable performance?

The statement could be easily said in reverse as "Dirty checking is a clever feature for a problem which knockout does not have". ES6 is using observables and angular is getting rid of dirty checking. The real world caught up to this answer and shown it to be false.

"Anything faster than 50 ms is imperceptible to humans" is not true. In testing we have found our customers can easily distinguish between 50ms update latency (20fps) and 16.6ms update latency (60fps). Scenes running at the former speed consistently get poorer overall "how did it feel" ratings even when people did not consciously register the framerate.

javascript - How does data binding work in AngularJS? - Stack Overflow

javascript angularjs data-binding
Rectangle 27 2561

Issues with change listeners:

AngularJS remembers the value and compares it to a previous value. This is basic dirty-checking. If there is a change in value, then it fires the change event.

The $apply() method, which is what you call when you are transitioning from a non-AngularJS world into an AngularJS world, calls $digest(). A digest is just plain old dirty-checking. It works on all browsers and is totally predictable.

To contrast dirty-checking (AngularJS) vs change listeners (KnockoutJS and Backbone.js): While dirty-checking may seem simple, and even inefficient (I will address that later), it turns out that it is semantically correct all the time, while change listeners have lots of weird corner cases and need things like dependency tracking to make it more semantically correct. KnockoutJS dependency tracking is a clever feature for a problem which AngularJS does not have.

  • The syntax is atrocious, since browsers do not support it natively. Yes, there are proxies, but they are not semantically correct in all cases, and of course there are no proxies on old browsers. The bottom line is that dirty-checking allows you to do POJO, whereas KnockoutJS and Backbone.js force you to inherit from their classes, and access your data through accessors.
  • Change coalescence. Suppose you have an array of items. Say you want to add items into an array, as you are looping to add, each time you add you are firing events on change, which is rendering the UI. This is very bad for performance. What you want is to update the UI only once, at the end. The change events are too fine-grained.
  • Change listeners fire immediately on a setter, which is a problem, since the change listener can further change data, which fires more change events. This is bad since on your stack you may have several change events happening at once. Suppose you have two arrays which need to be kept in sync for whatever reason. You can only add to one or the other, but each time you add you fire a change event, which now has an inconsistent view of the world. This is a very similar problem to thread locking, which JavaScript avoids since each callback executes exclusively and to completion. Change events break this since setters can have far-reaching consequences which are not intended and non obvious, which creates the thread problem all over again. It turns out that what you want to do is to delay the listener execution, and guarantee, that only one listener runs at a time, hence any code is free to change data, and it knows that no other code runs while it is doing so.

So the real question is this: How many comparisons can you do on a browser in 50ms? This is a hard question to answer as many factors come into play, but here is a test case: http://jsperf.com/angularjs-digest/6 which creates 10,000 watchers. On a modern browser this takes just under 6ms. On InternetExplorer8 it takes about 40ms. As you can see, this is not an issue even on slow browsers these days. There is a caveat: The comparisons need to be simple to fit into the time limit... Unfortunately it is way too easy to add a slow comparison into AngularJS, so it is easy to build slow applications when you don't know what you are doing. But we hope to have an answer by providing an instrumentation module, which would show you which are the slow comparisons.

It turns out that video games and GPUs use the dirty-checking approach, specifically because it is consistent. As long as they get over the monitor refresh rate (typically 50-60 Hz, or every 16.6-20 ms), any performance over that is a waste, so you're better off drawing more stuff, than getting FPS higher.

@Mark - yes, in KO you just add .extend({ throttle: 500 }) to wait 500 milliseconds after the last change event before acting on it.

This entire answer is great other than "As long as they get 50 fps, any performance over that is a waste, since the human eye can not appreciate it, so you're better off drawing more stuff, than getting fps higher." That statement is completely incorrect depending on your application. The eye can definitely appreciate more than 50 fps, and as the various problems with VR show (read any of the latest from John Carmack or Michael Abrash, especially the latter's GDC 2013 VR talk), 50 fps is actually way too slow. Other than that, your answer is great. I just don't want misinformation spreading.

Just wondering, if your app is like Twitter or a comment thread/forum, and you implement infinite scrolling based on Angular, you could run into the "2000 pieces of info" "limit". A single comment could easily have several variables for the author's name, profile img, content, datetime, and etc. Also, say we have a giant array for storing all the comments/posts, every dirty checking would require scanning of this array, am I right? This would make the browser a bit laggy at times which is a bad user experience. What do you suggest we do in this case to ensure reasonable performance?

The statement could be easily said in reverse as "Dirty checking is a clever feature for a problem which knockout does not have". ES6 is using observables and angular is getting rid of dirty checking. The real world caught up to this answer and shown it to be false.

"Anything faster than 50 ms is imperceptible to humans" is not true. In testing we have found our customers can easily distinguish between 50ms update latency (20fps) and 16.6ms update latency (60fps). Scenes running at the former speed consistently get poorer overall "how did it feel" ratings even when people did not consciously register the framerate.

javascript - How does data binding work in AngularJS? - Stack Overflow

javascript angularjs data-binding
Rectangle 27 10

As the function name suggests getElementsByClassName returns a collection not just one object. So you need to loop through them and apply the color to it.

document.getElementsByClassName()
                   ^_______

Plus your id part is invalid. Id cannot have spaces and also it shouldn't appear again on the page which is violated by:

<th id="colorswitcher A" onmouseover="document.getElementsByClassName('a').style.background='red'">a</th>
<th id="colorswitcher B" onmouseover="document.getElementsByClassName('a').style.background='blue'">b</th>

You can do it this way (You can look up what is a handler and try play yourself with it.), don't use inline attributes for handlers.

window.onload=function(){
    var aColl = document.getElementsByClassName('a'); //Cache the collection here, so that even a new element added with the same class later we can avoid querying this again by using the cached collection.
    var bColl = document.getElementsByClassName('b');

    document.getElementById('A').addEventListener('mouseover', function(){
        changeColor(aColl, 'red');
    });

    document.getElementById('B').addEventListener('mouseover', function(){
        changeColor(bColl, 'blue');
    });
}
function changeColor(coll, color){

    for(var i=0, len=coll.length; i<len; i++)
    {
        coll[i].style["background-color"] = color;
    }
}

If you are really trying to do it for some real work, then don't change the style attribute, instead define classes and add/remove classes on mouseover, mouseout events so that you get the power of css' cascading property.

Hi, thanks for the answer! I'm a bit of a noob, how would I go about looping through them? *edit: fixed IDs. thanks.

Might be important to mention that getElementsByClassName returns a live collection, and that's why you can "cache" aColl and bColl at the top of your function (otherwise, you'd have to re-query in the event handlers). Either way, great answer.

javascript - getElementsByClassName to change the style of elements wh...

javascript css onmouseover getelementsbyclassname
Rectangle 27 1

Events are bound to the elements and not to the ID attribute. Both the handlers are always executed when you click the button.

Also it is a good idea to avoid binding handlers using inline event handlers.

// Find the elemnt
var btn = document.getElementById('button');
// Data attribuet to keep tab of whether it is clicked or not
btn.dataset.clicked = "1";
// Attach event
btn.addEventListener('click', change);

function change() {
    var txt = 'Click to Change Me Back';
    // Will give you the truthy/falsy value
    if(!!this.dataset.clicked) {
        this.dataset.clicked = "";

       // First implementation

    } else {
        this.dataset.clicked = "1";
        txt = "Click Me";

        // The other case
    }
    this.innerHTML = txt;
}

Javascript changing button and onClick issue - Stack Overflow

javascript button onclick
Rectangle 27 256

onclick="doSomething();doSomethingElse();"

But really, you're better off not using onclick at all and attaching the event handler to the DOM node through your Javascript code. This is known as unobtrusive javascript.

Thanks for the reference to unobtrusive JS, I've come across this before, and I should refrain from writing obtrusive JS just because I'm lazy! xD

no probs... I also highly recommend jQuery which will really help you with your unobtrusive goal. You can easily attach event handlers to DOM elements and do much much more all unobtrusively. I've used it for 2 years now and never looked back.

If one called action in the onclick fails, the whole thing falls like a domino chain and the onclick fails to work.

is it a best practice to add 2 functions like what you suggested funct1();funct2() ? this might not always work , no ?

This html attribute is actually onclick="" not onClick="". It's a very common mistake.

html - How to call multiple JavaScript functions in onclick event? - S...

javascript html methods onclick
Rectangle 27 153

Security issues in similar approaches

This works similarly to the accepted answer, but is safe to use with untrusted user input.

As noted by Mike Samuel, doing this with a <div> instead of a <textarea> with untrusted user input is an XSS vulnerability, even if the <div> is never added to the DOM:

However, this attack is not possible against a <textarea> because there are no HTML elements that are permitted content of a <textarea>. Consequently, any HTML tags still present in the 'encoded' string will be automatically entity-encoded by the browser.

function decodeEntities(encodedString) {
    var textArea = document.createElement('textarea');
    textArea.innerHTML = encodedString;
    return textArea.value;
}

// Safe, and returns the correct answer
console.log(decodeEntities('<img src="nonexistent_image" onerror="alert(1337)">'))

Doing this using jQuery's .html() and .val() methods instead of using .innerHTML and .value is also insecure* for some versions of jQuery, even when using a textarea. This is because older versions of jQuery would deliberately and explicitly evaluate scripts contained in the string passed to .html(). Hence code like this shows an alert in jQuery 1.8:

// Shows alert
$('<textarea>').html('<script>alert(1337)</script>').text()
decodedString = textArea.value;
textArea.remove();
return decodedString;
if ('remove' in Element.prototype) textArea.remove();

@Werner As soon as the function has exited, there will be no more variables holding a reference to it so it will be automatically removed by the garbage collector.

javascript - How to decode HTML entities using jQuery? - Stack Overflo...

javascript jquery html
Rectangle 27 73

You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()

$(document).ready(function(){
    var js = "alert('B:' + this.id); return false;";
    // create a function from the "js" string
    var newclick = new Function(js);

    // clears onclick then sets click using jQuery
    $("#anchor").attr('onclick', '').click(newclick);
});

That should cancel the onClick function - and keep your "javascript from a string" as well.

The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.

Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().

onclick = eval("(function(){"+js+"})");
onclick = new Function(js);
Function()

Beware of this as well: jQuery unbind() vs removeAttr() see novogeek.com/post/2009/05/18/

JavaScript: changing the value of onclick with or without jQuery - Sta...

javascript jquery onclick attributes
Rectangle 27 55

<a href="#" onclick="someFunc()">Click me To fire some functions</a>
someFunc()
function someFunc() {
    showAlert();
    validate();
    anotherFunction();
    YetAnotherFunction();
}

IMHO, this is the true programmer's approach.

@b1nary.atr0phy nope. the programmer way is to add a href="" attribute for when user has no javascript. then, with javascript (so you know user supports it) you remove the href, and add event listeners to the event. that way, if another module of your code will listen to the same click, it does not get overwritten, or overwrite your code. read: developer.mozilla.org/en-US/docs/Web/API/Event

This might not work well if you have any arguments being passed to the functions, especially if you generate those arguments from a server-side language. It would be easier to build/maintain the code by appending the functions (with any arguments) within the server-side language rather than testing all possible iterations on both the server and client.

html - How to call multiple JavaScript functions in onclick event? - S...

javascript html methods onclick
Rectangle 27 19

Basically, in the first example you're binding the i inside the onclick handler directly to the i outside the onclick handler. So when the i outside the onclick handler changes, the i inside the onclick handler changes too.

In the second example, instead of binding it to the num in the onclick handler, you're passing it into a function, which then binds it to the num in the onclick handler. When you pass it into the function, the value of i is copied, not bound to num. So when i changes, num stays the same. The copy occurs because functions in JavaScript are "closures", meaning that once something is passed into the function, it's "closed" for outside modification.

I've read several answers for this topic trying to wrap my head around why. The last half of your last sentence turned the light on in my head finally,... thank you, thank you, thank you!

closures - Javascript infamous Loop issue? - Stack Overflow

javascript closures
Rectangle 27 321

Add this in your input element:

<input action="action" onclick="window.history.go(-1); return false;" type="button" value="Back" />

This doesn't work in all browsers for me, I had to do the following <input action="action" type="button" value="Back" onclick="window.history.go(-1); return false;" /> This answer is quite old, so it could have been an issue introduced into more modern versions of browsers. :)

Does this show the previous page from cache or reloads the previous page from the server?

What's the action="action" part for? And is it valid html??

html - Onclick javascript to make browser go back to previous page? - ...

javascript html browser javascript-events onclick
Rectangle 27 162

HTMLCollection
NodeList

In all modern browsers (pretty much anything other IE <= 8), you can call Array's forEach method, passing it the list of elements (be it HTMLCollection or NodeList) as the this value:

var els = document.getElementsByClassName("myclass");

Array.prototype.forEach.call(els, function(el) {
    // Do stuff here
    console.log(el.tagName);
});

// Or
[].forEach.call(els, function (el) {...});
[].forEach.call(elsArray, function () {...})

It's NOT a NodeList. It's an array-like object. I don't even think it has an instance type. querySelectorAll method returns a NodeList though.

@MaksimVi. You're absolutely right: DOM4 specifies that document.getElementsByClassName() should return an HTMLCollection (which is very similar but not a NodeList). Thanks for pointing out the mistake.

javascript - JS: iterating over result of getElementsByClassName using...

javascript foreach getelementsbyclassname
Rectangle 27 19

Basically, in the first example you're binding the i inside the onclick handler directly to the i outside the onclick handler. So when the i outside the onclick handler changes, the i inside the onclick handler changes too.

In the second example, instead of binding it to the num in the onclick handler, you're passing it into a function, which then binds it to the num in the onclick handler. When you pass it into the function, the value of i is copied, not bound to num. So when i changes, num stays the same. The copy occurs because functions in JavaScript are "closures", meaning that once something is passed into the function, it's "closed" for outside modification.

I've read several answers for this topic trying to wrap my head around why. The last half of your last sentence turned the light on in my head finally,... thank you, thank you, thank you!

closures - Javascript infamous Loop issue? - Stack Overflow

javascript closures
Rectangle 27 137

But the question itself is misleading

onClick
this.props.onClick.bind(null, this)

The event handler in your Parent can then access the component and event like so:

onClick: function (component, event) {
    // console.log(component, event);
  },
props

This isnt clear in the provided example because no props are actually being provided. This sample code might better support the question being asked:

It becomes much clearer in this example that you already know what the props of Child are.

If its truly about using a Childs props, you can avoid any hookup with Child altogether.

JSX has a spread attributes API I often use on components like Child. It takes all the props and applies them to a component. Child would look like this:

var Child = React.createClass({
  render: function () {
    return <a {...this.props}> {this.props.text} </a>;
  }
});

Allowing you to use the values directly in the Parent:

And there's no additional configuration required as you hookup additional Child components

var Parent = React.createClass({
  getInitialState: function () {
    return {
      text: "Click here",
      text2: "No, Click here",
    };
  },
  onClick: function (text) {
    alert(text);
  },
  render: function() {
    return <div>
      <Child onClick={this.onClick.bind(null, this.state.text)} text={this.state.text} />
      <Child onClick={this.onClick.bind(null, this.state.text2)} text={this.state.text2} />
    </div>;
  }
});

But I suspect thats not your actual use case. So lets dig further

The generic nature of the provided example is a hard to talk about. Ive created a component that demonstrations a practical use for the question above, implemented in a very Reacty way:

This component is a simple service calculator. You provide it with a list of services (with names and prices) and it will calculate a total the selected prices.

ServiceItem is the child-component in this example. It doesnt have many opinions about the outside world. It requires a few props, one of which is a function to be called when clicked.

<div onClick={this.props.handleClick.bind(this.props.index)} />

It does nothing but to call the provided handleClick callback with the provided index[source].

DTServicesCalculator is the parent-component is this example. Its also a child. Lets look.

DTServiceCalculator creates a list of child-component (ServiceItems) and provides them with props [source]. Its the parent-component of ServiceItem but it`s the child-component of the component passing it the list. It doesn't own the data. So it again delegates handling of the component to its parent-component source

<ServiceItem chosen={chosen} index={i} key={id} price={price} name={name} onSelect={this.props.handleServiceItem} />

handleServiceItem captures the index, passed from the child, and provides it to its parent [source]

handleServiceClick (index) {
  this.props.onSelect(index);
}

The concept of Ownership is an important one in React. I recommend reading more about it here.

In the example Ive shown, I keep delegating handling of an event up the component tree until we get to the component that owns the state.

When we finally get there, we handle the state selection/deselection like so [source]:

handleSelect (index) {
  let services = [this.state.services];
  services[index].chosen = (services[index].chosen) ? false : true;
  this.setState({ services: services });
}

Try keeping your outer-most components as opaque as possible. Strive to make sure that they have very few preferences about how a parent-component might choose to implement them.

Keep aware of who owns the data you are manipulating. In most cases, you will need to delegate event handling up the tree to the component that owns that state.

Thanks for the concise answer, it's really helped me understand React a bit better! I have a question along the same lines. I'm using Flux for pub / sub. Instead of passing the Child event handler up to the Parent like your example, it's possible to implement this as an 'action' and listen for it. Would you consider this a good alternative and use of Flux?

Thanks @Pathsofdesign! It would depend. Flux has this concept of Controller-Views. In this example, Parent might be such a Controller-View, while Child is just a dumb-View (component). Only Controller-Views should have knowledge of the application. In this case, you would still pass the Action from Parent to Child as a prop. As the Action itself is concerned, Flux has a strongly prescribed pattern for interacting between Actions to update Views. facebook.github.io/flux/docs/

onClick={this.onClick.bind(null, this.state.text)}
onClick={this.onClick}
onClick = ()=>{const text = this.state.text;..}

javascript - Pass props to parent component in React.js - Stack Overfl...

javascript reactjs
Rectangle 27 136

But the question itself is misleading

onClick
this.props.onClick.bind(null, this)

The event handler in your Parent can then access the component and event like so:

onClick: function (component, event) {
    // console.log(component, event);
  },
props

This isnt clear in the provided example because no props are actually being provided. This sample code might better support the question being asked:

It becomes much clearer in this example that you already know what the props of Child are.

If its truly about using a Childs props, you can avoid any hookup with Child altogether.

JSX has a spread attributes API I often use on components like Child. It takes all the props and applies them to a component. Child would look like this:

var Child = React.createClass({
  render: function () {
    return <a {...this.props}> {this.props.text} </a>;
  }
});

Allowing you to use the values directly in the Parent:

And there's no additional configuration required as you hookup additional Child components

var Parent = React.createClass({
  getInitialState: function () {
    return {
      text: "Click here",
      text2: "No, Click here",
    };
  },
  onClick: function (text) {
    alert(text);
  },
  render: function() {
    return <div>
      <Child onClick={this.onClick.bind(null, this.state.text)} text={this.state.text} />
      <Child onClick={this.onClick.bind(null, this.state.text2)} text={this.state.text2} />
    </div>;
  }
});

But I suspect thats not your actual use case. So lets dig further

The generic nature of the provided example is a hard to talk about. Ive created a component that demonstrations a practical use for the question above, implemented in a very Reacty way:

This component is a simple service calculator. You provide it with a list of services (with names and prices) and it will calculate a total the selected prices.

ServiceItem is the child-component in this example. It doesnt have many opinions about the outside world. It requires a few props, one of which is a function to be called when clicked.

<div onClick={this.props.handleClick.bind(this.props.index)} />

It does nothing but to call the provided handleClick callback with the provided index[source].

DTServicesCalculator is the parent-component is this example. Its also a child. Lets look.

DTServiceCalculator creates a list of child-component (ServiceItems) and provides them with props [source]. Its the parent-component of ServiceItem but it`s the child-component of the component passing it the list. It doesn't own the data. So it again delegates handling of the component to its parent-component source

<ServiceItem chosen={chosen} index={i} key={id} price={price} name={name} onSelect={this.props.handleServiceItem} />

handleServiceItem captures the index, passed from the child, and provides it to its parent [source]

handleServiceClick (index) {
  this.props.onSelect(index);
}

The concept of Ownership is an important one in React. I recommend reading more about it here.

In the example Ive shown, I keep delegating handling of an event up the component tree until we get to the component that owns the state.

When we finally get there, we handle the state selection/deselection like so [source]:

handleSelect (index) {
  let services = [this.state.services];
  services[index].chosen = (services[index].chosen) ? false : true;
  this.setState({ services: services });
}

Try keeping your outer-most components as opaque as possible. Strive to make sure that they have very few preferences about how a parent-component might choose to implement them.

Keep aware of who owns the data you are manipulating. In most cases, you will need to delegate event handling up the tree to the component that owns that state.

Thanks for the concise answer, it's really helped me understand React a bit better! I have a question along the same lines. I'm using Flux for pub / sub. Instead of passing the Child event handler up to the Parent like your example, it's possible to implement this as an 'action' and listen for it. Would you consider this a good alternative and use of Flux?

Thanks @Pathsofdesign! It would depend. Flux has this concept of Controller-Views. In this example, Parent might be such a Controller-View, while Child is just a dumb-View (component). Only Controller-Views should have knowledge of the application. In this case, you would still pass the Action from Parent to Child as a prop. As the Action itself is concerned, Flux has a strongly prescribed pattern for interacting between Actions to update Views. facebook.github.io/flux/docs/

onClick={this.onClick.bind(null, this.state.text)}
onClick={this.onClick}
onClick = ()=>{const text = this.state.text;..}

javascript - Pass props to parent component in React.js - Stack Overfl...

javascript reactjs
Rectangle 27 185

onclick
button
<button onclick="location.href = 'www.yoursite.com';" id="myButton" class="float-left submit-button" >Home</button>

But you shouldn't really have it inline like that, instead, put it in a JS block and give the button an ID:

<button id="myButton" class="float-left submit-button" >Home</button>

<script type="text/javascript">
    document.getElementById("myButton").onclick = function () {
        location.href = "www.yoursite.com";
    };
</script>

Do I need to have a form tag in this HTML that describes the method and submit action?

@Himansz Not if you're not going to submit the form. If it's a simple re-direction then you don't need a form.

javascript - How can I make a button redirect my page to another page?...

javascript jquery html
Rectangle 27 185

onclick
button
<button onclick="location.href = 'www.yoursite.com';" id="myButton" class="float-left submit-button" >Home</button>

But you shouldn't really have it inline like that, instead, put it in a JS block and give the button an ID:

<button id="myButton" class="float-left submit-button" >Home</button>

<script type="text/javascript">
    document.getElementById("myButton").onclick = function () {
        location.href = "www.yoursite.com";
    };
</script>

Do I need to have a form tag in this HTML that describes the method and submit action?

@Himansz Not if you're not going to submit the form. If it's a simple re-direction then you don't need a form.

javascript - How can I make a button redirect my page to another page?...

javascript jquery html
Rectangle 27 25

This is the code required if you're using only JavaScript and not jQuery

var el = document.getElementById("id");
el.addEventListener("click", function(){alert("click1 triggered")}, false);
el.addEventListener("click", function(){alert("click2 triggered")}, false);

this should be the right answer and the right way how to do it.

html - How to call multiple JavaScript functions in onclick event? - S...

javascript html methods onclick
Rectangle 27 88

history.back()
history.go(-1)

What's the browser support on that?

html - Onclick javascript to make browser go back to previous page? - ...

javascript html browser javascript-events onclick
Rectangle 27 69

<a href="javascript: history.go(-1)">Go Back</a>
<a href="##" onClick="history.go(-1); return false;">Go back</a>
For going 2 steps back history.go(-2)
For going 3 steps back history.go(-3)
For going 4 steps back history.go(-4)
and so on.......

@JeromeJ it is a link that does nothing if JavaScript isn't enabled/working (for whatever reason) on the page. If JavaScript is working, it takes the browser back one page.

html - Onclick javascript to make browser go back to previous page? - ...

javascript html browser javascript-events onclick
Rectangle 27 9

Your event handlers form a closure that remember a "live" pointer to the variables in the enclosing scope. So when they are actually executed, they have the last value imgSource and imgTitle had.

Instead, you can use this pattern to localize the variable values. This will create copies of source and title inside getClickHandler each time it is called. The returned function hence remembers the values in that iteration of the loop.

//Check those anchors with rel=litebox
for(i = 0;i < elem.length;i++){
    if(elem[i].rel == "litebox"){
        imgSource = elem[i].href.toString();
        imgTitle = elem[i].title;
        elem[i].childNodes[0].style.border="0px solid #fff";
        elem[i].onclick = getClickHandler(imgSource, imgTitle);
    }
}


//Brings up the image with focus
function getClickHandler(source,title){
    return function() {
        document.getElementById("liteBox").style.display = "block";
        document.getElementById("liteBox").innerHTML = "<h1>" + title + "</h1>" +
                                               "<img src='" + source + "'/><br />" +
                                               "<a href='#' onclick='liteBoxClose();'><img src='images/litebox_close.gif' border='0' alt='close'/></a>";
        document.getElementById("liteBoxBg").style.display = "block";
    }
}

javascript onclick, anonymous function - Stack Overflow

javascript function onclick anonymous