Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8410309
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T00:08:25+00:00 2026-06-10T00:08:25+00:00

I have a knockout viewModel with an array of items. I want to watch

  • 0

I have a knockout viewModel with an array of items. I want to watch one property (selected) on all the items and take action when it’s changed.

For that I have a SectionManager that will do that. I initialize the manager and set up subscribes for every item. The myid closure is not captured, it is always 3, the last value. Can somebody tell me where I’ve lost it?

Example: If you click on an item in the list, the asterisk will indicate if it is selected. That works. The subscribed function is called too, and the myid is written to the console, but that’s always 3.

John

HTML:

  <!DOCTYPE html>
  <html>
  <head>
     <title></title>
     <script type="text/javascript" src="Scripts/jquery-1.7.2.js"></script>
     <script type="text/javascript" src="Scripts/knockout-2.1.0.debug.js"></script>
     <script type="text/javascript" src="test.js"></script>
  </head>
  <body>
     <ul data-bind="foreach: roles">
        <li data-bind="click: toggle">
           <span data-bind="text: id"></span>
           <span data-bind="visible: selected">*</span>
        </li>
     </ul>
  </body>
  </html>

and this script:

  var roles = [
     { id: 1 },
     { id: 2, selected: true },
     { id: 3 }
  ];

  var viewModel = (function (roles) {
     var obj = {};
     var arr = [];
     for (var i = 0; i < roles.length; i++) {
        arr.push({
           id: roles[i].id,
           selected: ko.observable(roles[i].selected || false),
           toggle: function () {
              this.selected(!this.selected());
           }
        });
     }
     obj.roles = ko.observable(arr);

     return obj;
  })(roles);

  var sectionManager=(function(){
     return {
        init: function (roles) {
           for (var i = 0; i < roles.length; i++) {
              var item = roles[i];
              var myid = item.id;

              item.selected.subscribe(function () {
                 console.log(myid);  // ALWAYS 3!!
              });
           }
        }
     };
  })();

  $(function () {
     sectionManager.init(viewModel.roles());
     ko.applyBindings(viewModel);
  });
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T00:08:27+00:00Added an answer on June 10, 2026 at 12:08 am

    You are running into a classic issue caused by closures in JavaScript. In your loop there is really only one variable named myid. The functions that you are creating when subscribing to each item all have access to that same myid variable. At the end of the loop it’s value is 3, so when the handlers run they all report the value of that variable.

    There is a lot of reference out there for closures and scoping in JavaScript. For example, here is another SO question: JavaScript closure inside loops – simple practical example

    One way for you to handle this, is to not use the intermediate variable and ensure that your handler’s run with the current item.

    item.selected.subscribe(function () {
        console.log(this.id);
    }, item);
    

    In this example, the second argument defines the value of this when the function runs. So, it will run with the correct item as the context and you can access its properties from this.

    http://jsfiddle.net/rniemeyer/WV6g5/

    You could even use item.id in the second argument.

    As you pointed out below, you can certainly create a function that takes in your variable and have it return a function to create a closure around that specific value.

    var subscriber = function(id) 
    { 
        return function() { 
            console.log(id); 
        }; 
    }; 
    
    ...
    
    item.selected.subscribe(subscriber(myid)); 
    

    In the context of Knockout, I think that it is more practical to deal with your data item and ensure that it is this when your handler runs.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a Knockout observable array that I wish to edit from within Javascript
I am using knockout and have an array Properties and each Property can have
I have a page that requires jQuery.tmpl, but I want to use native knockout
I have a script that initializes knockout by applying an empty viewmodel to my
I have a Knockout Viewmodel that uses the mapping plugin. After mapping the JSON
i work with knockout, i have an observablearray (mappedCompaignByInterest) in my viewmodel that contains
I have a knockout model that is feeding my page and on a save
I have created a form with knockout that will allow the ability to give
I have the following table template that is rendered through knockout: <table class=gv data-bind=visible:
I am new to Knockout.js, I have created an observable array and initialized with

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.