Imran Rashid
Imran Rashid

Reputation: 1338

Knockout: how to access element inside the subscribe function

I am trying to get to the bound element from inside the subscribe callback. I have been trying to find something that could point me in the right direction but could not find any. Can you let me know how I can accomplish something like the following:

var ViewModel = {
    var self = this;
    self.Id = ko.observable();
    self.Id.subscribe(function(newvalue){
        //I want to get the element that the Id is bound to
        //How can I do that?
    });
}

Thanks.

Upvotes: 0

Views: 3153

Answers (3)

Jason Loki Smith
Jason Loki Smith

Reputation: 438

You need to bind what context "this" would have inside your subscribe method. like such:

Either bind explicitly:

 this.property.subscribe(function(newValue) {
                               this.something(newValue);
                       }.bind(this));

or you can do this:

this.property.subscribe(function(newValue) {
                           this.something(newValue);
                   }, this);

Both approaches have the same outcome.

Upvotes: 2

Rajesh
Rajesh

Reputation: 24955

I recently had the similar issue and fortunately had help from a brilliant person.

Code

for (var row in obj){
    if(typeof(obj[row]) == "function") {
        obj[row].subscribe(function(r) {
            return function(newValue) {
                var _fieldName = r;
                console.log(_fieldName, newValue);
                // Do your stuff
            };
        }(row));
    }
}

Explanation

Subscribe function requires a function and first parameter of this function is the value (New/Old). So Instead of writing an inline function, return a function of same signature, and bind value to this outer function.

Hope it helps.

Upvotes: 0

lante
lante

Reputation: 7346

Well, you can't on that way, but you can get the element on the change event:

HTML:

<input data-bind="value: foo, event: { change: helloElement.bind($data, foo, $element) }" />

JS:

var model = {
    foo: ko.observable(),
    helloElement: function (value, element) {
        console.log("Hi! I have the value " + value() + " and I live in the element: ", element);
    }
};

ko.applyBindings(model);

Working fiddle.

Upvotes: 1

Related Questions