1

From within a viewmodel I'm trying to dynamically push items to an observableArray. The ajax returns the data correctly.

html :

<li class="liTagulTagsChild" data-bind="click:$root.GetEmissions">/li>

javascript:

       var TagDetail = function (di_titre, di_diffusion) {
            this.di_titre = ko.observable(di_titre);
            this.di_diffusion = ko.observable(di_diffusion);               
        }

        var testA = [];
        this.test = ko.observableArray(testA);

        this.GetEmissions = function (c, event) {
            var element = event.target;
            var tag_id = element.getAttribute('tag_id');

            $.AjaxAntiforgery({
                url: 'Emission/GetDetailsByTagID/',
                data: {
                    tag_id: tag_id
                },
                success: function (result) {              
                        for (var i = 0; i < result.length; i++) {
                        var tD = new TagDetail(result[i].DI_TITRE, result[i].DI_DIFFUSION);
                        this.test.push(tD);
                    }

                }
            });
        }

Problem: From within the GetEmissions function I cannot push items to this.test because this.test is null (not defined).

In other words,

 this.test.push(tD);

fails. (null reference or not defined) A solution anyone ?

Ole EH Dufour
  • 2,968
  • 4
  • 23
  • 48

1 Answers1

2

In Javascript "this" doesn't mean what you think it means. Check out How to access the correct `this` context inside a callback?

Community
  • 1
  • 1
Jason Spake
  • 4,293
  • 2
  • 14
  • 22