Xepe
Xepe

Reputation: 235

knockout js, using subscribe after a change using jquery.

Is there a way to activate the subscribe, when we change something using jquery ?

for example:

var MyModel = function (){
 var self = this;
 this.ImageUrl= ko.observable("Image.jgp");
}

var Model = new MyModel (); 
ko.applyBindings(Model);
Model.ImageUrl.subscribe(function (NewValue)
{
console.log(NewValue);
})

<img data-bind:"attr{src: ImageUrl}" id ="image1" src = "" alt= "new image"/>

and I am using jquery to change the src:

$("#button1").click(function(){
$("#image1").attr("src","image2.jpg");
})

this is a little example, I am not sure if this is the best option.

Upvotes: 0

Views: 4627

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

The attr binding is a one-way binding, so it does not react to changes to the element (does not handle any events).

Knockout does include two helper functions called ko.dataFor and ko.contextFor that can give you the current data/context given a DOM element. Here are the docs that we have on it: http://knockoutjs.com/documentation/unobtrusive-event-handling.html.

So, basically, if you want to attach your event handler via jQuery, then you would want to use ko.dataFor to get your data and then update your ImageUrl observable directly.

Here is a sample: http://jsfiddle.net/rniemeyer/gbruu/

Upvotes: 1

Related Questions