Note that there are some explanatory texts on larger screens.

plurals
  1. POCorrect use of the this pointer in javascript for callbacks in knockout.js
    text
    copied!<p>I am a relatively experienced c# (and before that c++ Win32) developer, I am new to javascript and have a question regarding the <code>this</code> pointer.</p> <p>I am using knockout.js, and one function called subscribe accepts a <code>this</code> variable, that will be set inside the callback function.</p> <p>From my way of thinking from the Win32 days and C#, on any callback function i want a scope object which contains my state.</p> <p>In this case I have use the <code>this</code> javascript thing to set my callback scope.</p> <p>My questions are:</p> <ol> <li><p>Now everything works (<strong><a href="http://jsfiddle.net/g18c/DTdyM/25/" rel="nofollow">full fiddle here if you are interested</a></strong>), but have I done something terrible?</p></li> <li><p>Is there any reason <code>this</code> is used instead of passing in an explicit scope variable as a parameter (that would make things easier to understand as for me, this makes the workings kind of hidden).</p></li> <li><p>What is the intended use for <code>this</code>?</p></li> </ol> <p>From <a href="http://knockoutjs.com/documentation/observables.html" rel="nofollow">http://knockoutjs.com/documentation/observables.html</a> it says:</p> <p><strong>The subscribe function accepts three parameters: callback is the function that is called whenever the notification happens, target (optional) defines the value of this in the callback function, and event (optional; default is "change") is the name of the event to receive notification for. Example below</strong></p> <pre><code>myViewModel.personName.subscribe(function(oldValue) { alert("The person's previous name is " + oldValue); }, null, "beforeChange"); </code></pre> <p>My code snippet below:</p> <pre><code>var computedOptions = createComputedDepdency(viewModel[option.requires.target],option.data); viewModel[option.optionsName] = computedOptions; console.log("making callback scope object for: " + option.optionsName ); var callbackScope = { callbackName: option.optionsName, options: computedOptions, selectedValue: viewModel[option.selectedName] }; // when the list of available options changes, set the selected property to the first option computedOptions.subscribe(function () { var scope = this; console.log("my object: %o", scope); scope.selectedValue(scope.options()[0].sku); console.log("in subscribe function for..." + scope.callbackName); },callbackScope); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload