Jesus Rodriguez
Jesus Rodriguez

Reputation: 12018

Undefined when accessing to a viewModel object

Im trying a weird way to save the changes with a contenteditable span but I have a little problem:

This is my span:

<span data-bind="text: Content, event: { blur: viewModel.contentEdited}" contenteditable></span>

and the viewModel is like:

var viewModel = {
    notes: ko.observableArray([]),
    newNoteContent: ko.observable(),
    actualId: 0
};

viewModel.contentEdited = function () {
    alert(this.notes);
}

The template is binding to a note that is:

function note(id, date, content, category, color, background) {
    this.ID = id;
    this.Date = date;
    this.Content = content;
    this.Category = category;
    this.Color = color;
    this.Background = background;
}

the alert says "Undefined", is that because im creating another instance of the viewModel and the notes there is empty? The context of the templates is a note and that is outside the viewModel.

Thank you!

Upvotes: 0

Views: 389

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

In Knockout, you need to be careful with what the value of this is when your methods are called. When you are inside the items (notes), then this will be the array item.

The easiest way to handle this is to be explicit about the value of this. Knockout includes an implementation of the bind() function that allows you to effectively set the value of this for a function.

So, your function would look like:

viewModel.contentEdited = function () {
    alert(this.notes);
}.bind(viewModel);

Upvotes: 1

Related Questions