Rectangle 27 583

$observe() is a method on the Attributes object, and as such, it can only be used to observe/watch the value change of a DOM attribute. It is only used/called inside directives. Use $observe when you need to observe/watch a DOM attribute that contains interpolation (i.e., {{}}'s). E.g., attr1="Name: {{name}}", then in a directive: attrs.$observe('attr1', ...). (If you try scope.$watch(attrs.attr1, ...) it won't work because of the {{}}s -- you'll get undefined.) Use $watch for everything else.

$watch() is more complicated. It can observe/watch an "expression", where the expression can be either a function or a string. If the expression is a string, it is $parse'd (i.e., evaluated as an Angular expression) into a function. (It is this function that is called every digest cycle.) The string expression can not contain {{}}'s. $watch is a method on the Scope object, so it can be used/called wherever you have access to a scope object, hence in

  • a controller -- any controller -- one created via ng-view, ng-controller, or a directive controller
  • a linking function in a directive, since this has access to a scope as well
attr1="myModel.some_prop"
scope.$watch('myModel.some_prop', ...)
scope.$watch(attrs.attr1, ...)
scope.$watch(attrs['attr1'], ...)
attrs.$observe('attr1')
myModel.some_prop

As discussed in comments on @PrimosK's answer, all $observes and $watches are checked every digest cycle.

Directives with isolate scopes are more complicated. If the '@' syntax is used, you can $observe or $watch a DOM attribute that contains interpolation (i.e., {{}}'s). (The reason it works with $watch is because the '@' syntax does the interpolation for us, hence $watch sees a string without {{}}'s.) To make it easier to remember which to use when, I suggest using $observe for this case also.

To help test all of this, I wrote a Plunker that defines two directives. One (d1) does not create a new scope, the other (d2) creates an isolate scope. Each directive has the same six attributes. Each attribute is both $observe'd and $watch'ed.

<div d1 attr1="{{prop1}}-test" attr2="prop2" attr3="33" attr4="'a_string'"
        attr5="a_string" attr6="{{1+aNumber}}"></div>

Look at the console log to see the differences between $observe and $watch in the linking function. Then click the link and see which $observes and $watches are triggered by the property changes made by the click handler.

Notice that when the link function runs, any attributes that contain {{}}'s are not evaluated yet (so if you try to examine the attributes, you'll get undefined). The only way to see the interpolated values is to use $observe (or $watch if using an isolate scope with '@'). Therefore, getting the values of these attributes is an asynchronous operation. (And this is why we need the $observe and $watch functions.)

Sometimes you don't need $observe or $watch. E.g., if your attribute contains a number or a boolean (not a string), just evaluate it once: attr1="22", then in, say, your linking function: var count = scope.$eval(attrs.attr1). If it is just a constant string attr1="my string" then just use attrs.attr1 in your directive (no need for $eval()).

ng-src/ng-href
attr.$observe
scope.$watch

@tamakisquare, they are interchangeable when using the @ syntax. I believe there is no performance difference (but I haven't looked at the actual source code).

javascript - AngularJS : Difference between the $observe and $watch me...

javascript angularjs
Rectangle 27 580

$observe() is a method on the Attributes object, and as such, it can only be used to observe/watch the value change of a DOM attribute. It is only used/called inside directives. Use $observe when you need to observe/watch a DOM attribute that contains interpolation (i.e., {{}}'s). E.g., attr1="Name: {{name}}", then in a directive: attrs.$observe('attr1', ...). (If you try scope.$watch(attrs.attr1, ...) it won't work because of the {{}}s -- you'll get undefined.) Use $watch for everything else.

$watch() is more complicated. It can observe/watch an "expression", where the expression can be either a function or a string. If the expression is a string, it is $parse'd (i.e., evaluated as an Angular expression) into a function. (It is this function that is called every digest cycle.) The string expression can not contain {{}}'s. $watch is a method on the Scope object, so it can be used/called wherever you have access to a scope object, hence in

  • a controller -- any controller -- one created via ng-view, ng-controller, or a directive controller
  • a linking function in a directive, since this has access to a scope as well
attr1="myModel.some_prop"
scope.$watch('myModel.some_prop', ...)
scope.$watch(attrs.attr1, ...)
scope.$watch(attrs['attr1'], ...)
attrs.$observe('attr1')
myModel.some_prop

As discussed in comments on @PrimosK's answer, all $observes and $watches are checked every digest cycle.

Directives with isolate scopes are more complicated. If the '@' syntax is used, you can $observe or $watch a DOM attribute that contains interpolation (i.e., {{}}'s). (The reason it works with $watch is because the '@' syntax does the interpolation for us, hence $watch sees a string without {{}}'s.) To make it easier to remember which to use when, I suggest using $observe for this case also.

To help test all of this, I wrote a Plunker that defines two directives. One (d1) does not create a new scope, the other (d2) creates an isolate scope. Each directive has the same six attributes. Each attribute is both $observe'd and $watch'ed.

<div d1 attr1="{{prop1}}-test" attr2="prop2" attr3="33" attr4="'a_string'"
        attr5="a_string" attr6="{{1+aNumber}}"></div>

Look at the console log to see the differences between $observe and $watch in the linking function. Then click the link and see which $observes and $watches are triggered by the property changes made by the click handler.

Notice that when the link function runs, any attributes that contain {{}}'s are not evaluated yet (so if you try to examine the attributes, you'll get undefined). The only way to see the interpolated values is to use $observe (or $watch if using an isolate scope with '@'). Therefore, getting the values of these attributes is an asynchronous operation. (And this is why we need the $observe and $watch functions.)

Sometimes you don't need $observe or $watch. E.g., if your attribute contains a number or a boolean (not a string), just evaluate it once: attr1="22", then in, say, your linking function: var count = scope.$eval(attrs.attr1). If it is just a constant string attr1="my string" then just use attrs.attr1 in your directive (no need for $eval()).

ng-src/ng-href
attr.$observe
scope.$watch

@tamakisquare, they are interchangeable when using the @ syntax. I believe there is no performance difference (but I haven't looked at the actual source code).

javascript - AngularJS : Difference between the $observe and $watch me...

javascript angularjs
Rectangle 27 580

$observe() is a method on the Attributes object, and as such, it can only be used to observe/watch the value change of a DOM attribute. It is only used/called inside directives. Use $observe when you need to observe/watch a DOM attribute that contains interpolation (i.e., {{}}'s). E.g., attr1="Name: {{name}}", then in a directive: attrs.$observe('attr1', ...). (If you try scope.$watch(attrs.attr1, ...) it won't work because of the {{}}s -- you'll get undefined.) Use $watch for everything else.

$watch() is more complicated. It can observe/watch an "expression", where the expression can be either a function or a string. If the expression is a string, it is $parse'd (i.e., evaluated as an Angular expression) into a function. (It is this function that is called every digest cycle.) The string expression can not contain {{}}'s. $watch is a method on the Scope object, so it can be used/called wherever you have access to a scope object, hence in

  • a controller -- any controller -- one created via ng-view, ng-controller, or a directive controller
  • a linking function in a directive, since this has access to a scope as well
attr1="myModel.some_prop"
scope.$watch('myModel.some_prop', ...)
scope.$watch(attrs.attr1, ...)
scope.$watch(attrs['attr1'], ...)
attrs.$observe('attr1')
myModel.some_prop

As discussed in comments on @PrimosK's answer, all $observes and $watches are checked every digest cycle.

Directives with isolate scopes are more complicated. If the '@' syntax is used, you can $observe or $watch a DOM attribute that contains interpolation (i.e., {{}}'s). (The reason it works with $watch is because the '@' syntax does the interpolation for us, hence $watch sees a string without {{}}'s.) To make it easier to remember which to use when, I suggest using $observe for this case also.

To help test all of this, I wrote a Plunker that defines two directives. One (d1) does not create a new scope, the other (d2) creates an isolate scope. Each directive has the same six attributes. Each attribute is both $observe'd and $watch'ed.

<div d1 attr1="{{prop1}}-test" attr2="prop2" attr3="33" attr4="'a_string'"
        attr5="a_string" attr6="{{1+aNumber}}"></div>

Look at the console log to see the differences between $observe and $watch in the linking function. Then click the link and see which $observes and $watches are triggered by the property changes made by the click handler.

Notice that when the link function runs, any attributes that contain {{}}'s are not evaluated yet (so if you try to examine the attributes, you'll get undefined). The only way to see the interpolated values is to use $observe (or $watch if using an isolate scope with '@'). Therefore, getting the values of these attributes is an asynchronous operation. (And this is why we need the $observe and $watch functions.)

Sometimes you don't need $observe or $watch. E.g., if your attribute contains a number or a boolean (not a string), just evaluate it once: attr1="22", then in, say, your linking function: var count = scope.$eval(attrs.attr1). If it is just a constant string attr1="my string" then just use attrs.attr1 in your directive (no need for $eval()).

ng-src/ng-href
attr.$observe
scope.$watch

@tamakisquare, they are interchangeable when using the @ syntax. I believe there is no performance difference (but I haven't looked at the actual source code).

javascript - AngularJS : Difference between the $observe and $watch me...

javascript angularjs
Rectangle 27 20

If I understand your question right you are asking what is difference if you register listener callback with $watch or if you do it with $observe.

Callback registerd with $watch is fired when $digest is executed. Please take a look at the docs for more info.

Callback registered with $observe are called when value changes of attributes that contain interpolation (e.g. attr="{{notJetInterpolated}}").

Inside directive you can use both of them on very similar way:

attrs.$observe('attrYouWatch', function() {
         // body
    });
scope.$watch(attrs['attrYouWatch'], function() {
         // body
    });

Actually, since every change gets reflected in $digest phase, it is safe to assume that the $observe callback will be called in $digest. And $watch callback will also be called in $digest but whenever the value is changed. I think they do the exact same job: "watch the expression, call callback the value changes". The keyword difference is possibly just syntactic sugar for not confusing the developer.

@fastreload... Thanks for the wonderful explanation. If I understood correctly, Observers are for Angular Expressions. Am I right?

@Abilash observers are for watching dom attributes, not just expressions. So if you change the attribute value by yourself, it would be reflected in the next digest cycle.

javascript - AngularJS : Difference between the $observe and $watch me...

javascript angularjs
Rectangle 27 20

If I understand your question right you are asking what is difference if you register listener callback with $watch or if you do it with $observe.

Callback registerd with $watch is fired when $digest is executed. Please take a look at the docs for more info.

Callback registered with $observe are called when value changes of attributes that contain interpolation (e.g. attr="{{notJetInterpolated}}").

Inside directive you can use both of them on very similar way:

attrs.$observe('attrYouWatch', function() {
         // body
    });
scope.$watch(attrs['attrYouWatch'], function() {
         // body
    });

Actually, since every change gets reflected in $digest phase, it is safe to assume that the $observe callback will be called in $digest. And $watch callback will also be called in $digest but whenever the value is changed. I think they do the exact same job: "watch the expression, call callback the value changes". The keyword difference is possibly just syntactic sugar for not confusing the developer.

@fastreload... Thanks for the wonderful explanation. If I understood correctly, Observers are for Angular Expressions. Am I right?

@Abilash observers are for watching dom attributes, not just expressions. So if you change the attribute value by yourself, it would be reflected in the next digest cycle.

javascript - AngularJS : Difference between the $observe and $watch me...

javascript angularjs
Rectangle 27 20

If I understand your question right you are asking what is difference if you register listener callback with $watch or if you do it with $observe.

Callback registerd with $watch is fired when $digest is executed. Please take a look at the docs for more info.

Callback registered with $observe are called when value changes of attributes that contain interpolation (e.g. attr="{{notJetInterpolated}}").

Inside directive you can use both of them on very similar way:

attrs.$observe('attrYouWatch', function() {
         // body
    });
scope.$watch(attrs['attrYouWatch'], function() {
         // body
    });

Actually, since every change gets reflected in $digest phase, it is safe to assume that the $observe callback will be called in $digest. And $watch callback will also be called in $digest but whenever the value is changed. I think they do the exact same job: "watch the expression, call callback the value changes". The keyword difference is possibly just syntactic sugar for not confusing the developer.

@fastreload... Thanks for the wonderful explanation. If I understood correctly, Observers are for Angular Expressions. Am I right?

@Abilash observers are for watching dom attributes, not just expressions. So if you change the attribute value by yourself, it would be reflected in the next digest cycle.

javascript - AngularJS : Difference between the $observe and $watch me...

javascript angularjs
Rectangle 27 40

Consider using MutationObserver. These observers are designed to react to changes in the DOM, and as a performant replacement to Mutation Events.

  • Fires when any change occurs, which is difficult to achieve by listening to key events as suggested by other answers. For example, all of these work well: drag & drop, italicizing, copy/cut/paste through context menu.
  • Designed with performance in mind.
  • Simple, straightforward code. It's a lot easier to understand and debug code that listens to one event rather than code that listens to 10 events.
  • Requires a very recent version of Firefox (14.0+), Chrome (18+), or IE (11+).
  • Not a lot of information available yet on best practices or case studies
  • Mozilla has an excellent page on the API

It's not quite the same as the HTML5 input event (which is supported for contenteditable in all the WebKit and Mozilla browsers that support mutation observers), since DOM mutation could occur via script as well as user input, but it's a viable solution for those browsers. I imagine it could harm performance more than the input event too, but I have no hard evidence for this.

+1, but did you realize that Mutation Events do not report the effects of line feed in a contenteditable? Press enter in your snippet.

@citykid: That's because the snippet is only watching for changes to character data. It's possible to observe DOM structural changes too. See jsfiddle.net/4n2Gz/1, for example.

thx for the fiddle, good point. how could i miss that.

javascript - contenteditable change events - Stack Overflow

javascript jquery html5 contenteditable
Rectangle 27 39

Consider using MutationObserver. These observers are designed to react to changes in the DOM, and as a performant replacement to Mutation Events.

  • Fires when any change occurs, which is difficult to achieve by listening to key events as suggested by other answers. For example, all of these work well: drag & drop, italicizing, copy/cut/paste through context menu.
  • Designed with performance in mind.
  • Simple, straightforward code. It's a lot easier to understand and debug code that listens to one event rather than code that listens to 10 events.
  • Requires a very recent version of Firefox (14.0+), Chrome (18+), or IE (11+).
  • Not a lot of information available yet on best practices or case studies
  • Mozilla has an excellent page on the API

It's not quite the same as the HTML5 input event (which is supported for contenteditable in all the WebKit and Mozilla browsers that support mutation observers), since DOM mutation could occur via script as well as user input, but it's a viable solution for those browsers. I imagine it could harm performance more than the input event too, but I have no hard evidence for this.

+1, but did you realize that Mutation Events do not report the effects of line feed in a contenteditable? Press enter in your snippet.

@citykid: That's because the snippet is only watching for changes to character data. It's possible to observe DOM structural changes too. See jsfiddle.net/4n2Gz/1, for example.

thx for the fiddle, good point. how could i miss that.

javascript - contenteditable change events - Stack Overflow

javascript jquery html5 contenteditable
Rectangle 27 162

var observeDOM = (function(){
    var MutationObserver = window.MutationObserver || window.WebKitMutationObserver,
        eventListenerSupported = window.addEventListener;

    return function(obj, callback){
        if( MutationObserver ){
            // define a new observer
            var obs = new MutationObserver(function(mutations, observer){
                if( mutations[0].addedNodes.length || mutations[0].removedNodes.length )
                    callback();
            });
            // have the observer observe foo for changes in children
            obs.observe( obj, { childList:true, subtree:true });
        }
        else if( eventListenerSupported ){
            obj.addEventListener('DOMNodeInserted', callback, false);
            obj.addEventListener('DOMNodeRemoved', callback, false);
        }
    };
})();

// Observe a specific DOM element:
observeDOM( document.getElementById('dom_element') ,function(){ 
    console.log('dom changed');
});

it seems to work pretty nicely for new DOM nodes. Can we adapt it to also handle dom node changes (at least the DOM node values/text?)

@SebastienLorber - who is "we"? you, as a programmer, can take this code and use it however you wish. just read on the MDN which things you can observe the DOM for and which you cannot.

mutations, observer

This helped me a lot, but how do I "unbind" this? Say I want to watch for a change only once, but do this on multiple occasions? oberserveDOM = null obviously won't work...

@f0ster - I said only because those are the ones I had provided in my example code and any person with common sense will understand they could use whatever else the API allows. for this example I only used those two.

javascript - Detect changes in the DOM - Stack Overflow

javascript dom mutation-events mutation-observers
Rectangle 27 4

I would use setTimeout to call a function that uses JQuery to make an $.ajax call. When it returns JSON data, set that data as your view model and finally, setTimeout again to call the function.

javascript - How to use KnockoutJS to observe data on server via AJAX?...

javascript ajax mvvm knockout.js
Rectangle 27 383

Several years later, there is now officially a better solution. DOM4 Mutation Observers are the replacement for deprecated DOM3 mutation events. They are currently implemented in modern browsers as MutationObserver (or as the vendor-prefixed WebKitMutationObserver in old versions of Chrome):

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // fired when a mutation occurs
    console.log(mutations, observer);
    // ...
});

// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
  subtree: true,
  attributes: true
  //...
});

This example listens for DOM changes on document and its entire subtree, and it will fire on changes to element attributes as well as structural changes. The draft spec has a full list of valid mutation listener properties:

  • Set to true if mutations to target's data are to be observed.
  • Set to true if mutations to not just target, but also target's descendants are to be observed.
attributes
true
characterData
  • Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed.

(This list is current as of April 2014; you may check the specification for any changes.)

@AshrafBashir I see the sample working fine in Firefox 19.0.2: I see ([{}]) logged to the console, which shows the expected MutationRecord when I click on it. Please check again, as it might have been a temporary technical failure in JSFiddle. I have not tested it in IE yet, since i don't have IE 10, which is currently the only version to support mutation events.

@LS Thanks, I've updated the link, removed the bit about the green box, and edited the entire list into my answer (just in case of future link rot).

Is there a JavaScript/jQuery DOM change listener? - Stack Overflow

javascript jquery google-chrome-extension
Rectangle 27 380

Several years later, there is now officially a better solution. DOM4 Mutation Observers are the replacement for deprecated DOM3 mutation events. They are currently implemented in modern browsers as MutationObserver (or as the vendor-prefixed WebKitMutationObserver in old versions of Chrome):

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // fired when a mutation occurs
    console.log(mutations, observer);
    // ...
});

// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
  subtree: true,
  attributes: true
  //...
});

This example listens for DOM changes on document and its entire subtree, and it will fire on changes to element attributes as well as structural changes. The draft spec has a full list of valid mutation listener properties:

  • Set to true if mutations to target's data are to be observed.
  • Set to true if mutations to not just target, but also target's descendants are to be observed.
attributes
true
characterData
  • Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed.

(This list is current as of April 2014; you may check the specification for any changes.)

@AshrafBashir I see the sample working fine in Firefox 19.0.2: I see ([{}]) logged to the console, which shows the expected MutationRecord when I click on it. Please check again, as it might have been a temporary technical failure in JSFiddle. I have not tested it in IE yet, since i don't have IE 10, which is currently the only version to support mutation events.

@LS Thanks, I've updated the link, removed the bit about the green box, and edited the entire list into my answer (just in case of future link rot).

Is there a JavaScript/jQuery DOM change listener? - Stack Overflow

javascript jquery google-chrome-extension
Rectangle 27 373

Several years later, there is now officially a better solution. DOM4 Mutation Observers are the replacement for deprecated DOM3 mutation events. They are currently implemented in modern browsers as MutationObserver (or as the vendor-prefixed WebKitMutationObserver in old versions of Chrome):

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // fired when a mutation occurs
    console.log(mutations, observer);
    // ...
});

// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
  subtree: true,
  attributes: true
  //...
});

This example listens for DOM changes on document and its entire subtree, and it will fire on changes to element attributes as well as structural changes. The draft spec has a full list of valid mutation listener properties:

  • Set to true if mutations to target's data are to be observed.
  • Set to true if mutations to not just target, but also target's descendants are to be observed.
attributes
true
characterData
  • Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed.

(This list is current as of April 2014; you may check the specification for any changes.)

@AshrafBashir I see the sample working fine in Firefox 19.0.2: I see ([{}]) logged to the console, which shows the expected MutationRecord when I click on it. Please check again, as it might have been a temporary technical failure in JSFiddle. I have not tested it in IE yet, since i don't have IE 10, which is currently the only version to support mutation events.

@LS Thanks, I've updated the link, removed the bit about the green box, and edited the entire list into my answer (just in case of future link rot).

Is there a JavaScript/jQuery DOM change listener? - Stack Overflow

javascript jquery google-chrome-extension
Rectangle 27 373

Several years later, there is now officially a better solution. DOM4 Mutation Observers are the replacement for deprecated DOM3 mutation events. They are currently implemented in modern browsers as MutationObserver (or as the vendor-prefixed WebKitMutationObserver in old versions of Chrome):

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // fired when a mutation occurs
    console.log(mutations, observer);
    // ...
});

// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
  subtree: true,
  attributes: true
  //...
});

This example listens for DOM changes on document and its entire subtree, and it will fire on changes to element attributes as well as structural changes. The draft spec has a full list of valid mutation listener properties:

  • Set to true if mutations to target's data are to be observed.
  • Set to true if mutations to not just target, but also target's descendants are to be observed.
attributes
true
characterData
  • Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed.

(This list is current as of April 2014; you may check the specification for any changes.)

@AshrafBashir I see the sample working fine in Firefox 19.0.2: I see ([{}]) logged to the console, which shows the expected MutationRecord when I click on it. Please check again, as it might have been a temporary technical failure in JSFiddle. I have not tested it in IE yet, since i don't have IE 10, which is currently the only version to support mutation events.

@LS Thanks, I've updated the link, removed the bit about the green box, and edited the entire list into my answer (just in case of future link rot).

Is there a JavaScript/jQuery DOM change listener? - Stack Overflow

javascript jquery google-chrome-extension
Rectangle 27 373

Several years later, there is now officially a better solution. DOM4 Mutation Observers are the replacement for deprecated DOM3 mutation events. They are currently implemented in modern browsers as MutationObserver (or as the vendor-prefixed WebKitMutationObserver in old versions of Chrome):

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // fired when a mutation occurs
    console.log(mutations, observer);
    // ...
});

// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
  subtree: true,
  attributes: true
  //...
});

This example listens for DOM changes on document and its entire subtree, and it will fire on changes to element attributes as well as structural changes. The draft spec has a full list of valid mutation listener properties:

  • Set to true if mutations to target's data are to be observed.
  • Set to true if mutations to not just target, but also target's descendants are to be observed.
attributes
true
characterData
  • Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed.

(This list is current as of April 2014; you may check the specification for any changes.)

@AshrafBashir I see the sample working fine in Firefox 19.0.2: I see ([{}]) logged to the console, which shows the expected MutationRecord when I click on it. Please check again, as it might have been a temporary technical failure in JSFiddle. I have not tested it in IE yet, since i don't have IE 10, which is currently the only version to support mutation events.

@LS Thanks, I've updated the link, removed the bit about the green box, and edited the entire list into my answer (just in case of future link rot).

Is there a JavaScript/jQuery DOM change listener? - Stack Overflow

javascript jquery google-chrome-extension
Rectangle 27 57

There is no way to differentiate it from newest Web Browsers.

The steps below describe what user agents must do for a simple cross-origin request

Apply the make a request steps and observe the request rules below while making the request.

If the manual redirect flag is unset and the response has an HTTP status code of 301, 302, 303, 307, or 308

If the end user cancels the request

If there is a network error In case of DNS errors, TLS negotiation failure, or other type of network errors, apply the network error steps. Do not request any kind of end user interaction.

Otherwise Perform a resource sharing check. If it returns fail, apply the network error steps. Otherwise, if it returns pass, terminate this algorithm and set the cross-origin request status to success. Do not actually terminate the request.

As you can read, network errors does not include HTTP response that include errors, that is why you will get always 0 as status code, and "" as error.

Note: The following examples were made using Google Chrome Version 43.0.2357.130 and against an environment that I've created to emulate OP one. Code to the set it up is at the bottom of the answer.

I though that an approach To work around this would be make a secondary request over HTTP instead of HTTPS as This answer but I've remembered that is not possible due that newer versions of browsers block mixed content.

That means that the Web Browser will not allow a request over HTTP if you are using HTTPS and vice versa.

This has been like this since few years ago but older Web Browser versions like Mozilla Firefox below it versions 23 allow it.

Making a HTTP request from HTTPS usign Web Broser console

var request = new XMLHttpRequest();
request.open('GET', "http://localhost:8001", true);
request.onload = function () {
    console.log(request.responseText);
};
request.onerror = function () {
    console.log(request.responseText);
};
request.send();

will result in the following error:

Same error will appear in the browser console if you try to do this in other ways as adding an Iframe.

<iframe src="http://localhost:8001"></iframe>

Using Socket connection was also Posted as an answer, I was pretty sure that the result will be the same / similar but I've give it a try.

Trying to Open a socket connection from the Web Broswer using HTTPS to a non Secure socket endpoint will end in mixed content errors.

new WebSocket("ws://localhost:8001", "protocolOne");

1) Mixed Content: The page at 'https://localhost:8000/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://localhost:8001/'. This request has been blocked; this endpoint must be available over WSS.

2) Uncaught DOMException: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.

Then I've tried to connect to a wss endpoint too see If I could read some information about network connection errors:

var exampleSocket = new WebSocket("wss://localhost:8001", "protocolOne");
exampleSocket.onerror = function(e) {
    console.log(e);
}

Executing snippet above with Server turned On

WebSocket connection to 'wss://localhost:8001/' failed: WebSocket opening handshake was canceled

But again, the error that the "onerror function" output to the console have not any tip to differentiate one error of the other.

Using a proxy as this answer suggest could work but only if the "target" server has public access.

This was not the case here, so trying to implement a proxy in this scenario will lead Us to the same problem.

I've created two Nodejs HTTPS servers, that use self signed certificates:

var https = require('https');
var fs = require('fs');

var options = {
    key: fs.readFileSync('./certs/key.pem'),
    cert: fs.readFileSync('./certs/key-cert.pem')
};

https.createServer(options, function (req, res) {
    res.writeHead(200);
    res.end("hello world\n");
}).listen(8000);

To make it work you need to have Nodejs Installed, Need to generate separated certificates for each server and store it in the folders certs and certs2 accordingly.

node applicationServer.js
node targetServer.js

This is the most complete answer so far. It shows that you have actually done some research work and testing. I see you have tried every possible way to perform this and all scenarios are really well explained. You have also provided example code to quickly set up a test environment! Really good work! Thanks for the insight!

javascript - Determine if ajax call failed due to insecure response or...

javascript jquery ajax https cors
Rectangle 27 14

I don't think knockout has a built-in way to observe changes to child elements. If I understand your question, when someone changes the name you want a change to details as an entity to be noticed. Can you give a concrete example of how you would use this? Would you use a subscription to the details observable to perform some action?

The reason your code doesn't make details an observable is because javascript is pass by value, so changing the value of the 'object' argument in your function doesn't change the actual value you passed, only the value of the argument inside your function.

If changes will automatically propagate to the parents, this should make all children observable I think, but your root that you pass the first time should already be an observable.

// object should already be observable
var makeChildrenObservables = function (object) {
    if(!ko.isObservable(object)) return;

    // Loop through its children
    for (var child in object()) {
        if (!ko.isObservable(object()[child])) {
            object()[child] = ko.observable(object()[child]);
        }
        makeChildrenObservables(object()[child]);
    }
};

I need this so I can change the color on a frame containing both name and surname. If any of the two changes, I set it to yellow. This is just an example, but that's what I have in mind. Knockout.js triggers a change for the parent if any of the children was changed, so yes, it would work. And is there a way to pass the object by reference, not by value? What if I use some kind of extension function (jQuery.extend maybe?) that does not change the original pointer but the value it references?

By using computed observables, it works. As soon as you change either the firstName or lastName, fullName gets triggered. This way you can track changes in any of elements in the structure. The function @jason-goemaat posted works (thank you!), but there's the need to know if it has already been applied. I have setup a function that sets the JS and makes everything an observable by itself. :D

How that works is that knockout runs the computed and traces what is accessed, adding a dependency for each. If you're using the individual observables in your computed anyway, there's no point in making the parent observable. I think what you need to do to make this automatic would be to create a function on your roar (or each object) and subscribe all children to it...

As promised, this is the result of what I asked here. It's an extension to knockout.js that provides REST methods to entities and a nice undo.

javascript - Knockout.js Make every nested object an Observable - Stac...

javascript mvvm knockout.js knockout-mapping-plugin knockout-2.0
Rectangle 27 7

You're right, I can't get any state change events to fire either once already in that state. Until, and if that functionality becomes available to use through that api someday, here's a semi-hacky solution for this. We can just leverage ng-click and use some silly logic to appease QA (in your case). Also, I don't know your controller implementation, so I placed my suggestion on $rootScope in .run in this example for simplicity and visibility, but integrate accordingly if you choose to do so. Observe the following example...

<a ui-sref="about" ng-click="sillyQA()">About</a>
.run(['$rootScope', '$state', function($rootScope, $state) {

    $rootScope.sillyQA = function() {
        if($state.current.name === 'about') {
            $state.go('about', {}, { reload: true });
        }
    }

    // -- just to see our about => about state 'change'
    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
        console.log('toState:   ' + toState.name );
        console.log('fromState: ' + (fromState.name || 'Just got there! click again!'));
    })
}]);

Thank you, nicely explained! I was more irritated when I received that request from QA. Because the user can always refresh the browser window if reload is needed. I don't see a point of clicking the same link again to reload it. LOL

@TonyGW I hear where you're coming from! I can only imagine a situation where there is a constant feed, such as the newest questions on SO. I could click the logo all day long if I wanted to "refresh" my feed, rather than explicitly refreshing my browser. Either way happy coding and I am glad this was able to help :)

Actually, the page contains a form for user input only. It doesn't receive any data from anywhere. QA people drive me crazy sometimes...

I honestly do not think this should be an accepted answer because there is a good reason for state change events not firing when you're in that state (like, one of the fundamental things behind single-page applications). This is also pretty poor practice in AngularJS/ui-router because you're adding unnecessary logic overhead to your controller, or in the worst case $rootScope.

Thanks for your input. I thought I made it pretty apparent that $rootScope was only for simple demonstration and to "implement accordingly" because the OP didn't share any controller logic. Also, if you read the question, this isn't about best practice, it's about solving a unique situation given a requirement. If you don't think this should be the accepted answer feel free to post your own. Enlighten us.

javascript - AngularJS with ui.router: reload page when clicking the s...

javascript html angularjs angular-ui-router reload
Rectangle 27 6

Hi I have checked the site you posted an was able to observe what you want to achieve.

document.getElementById('notClickable').ondragstart = function() { return false; };
//upon start of drag of the selected image, it immediately returns false, or cancels the event.

javascript - Disable anchor link click + drag in HTML page / Swipe a c...

javascript html hyperlink
Rectangle 27 6

Hi I have checked the site you posted an was able to observe what you want to achieve.

document.getElementById('notClickable').ondragstart = function() { return false; };
//upon start of drag of the selected image, it immediately returns false, or cancels the event.

javascript - Disable anchor link click + drag in HTML page / Swipe a c...

javascript html hyperlink