Jonas
Jonas

Reputation: 5149

Inheritance and knockoutjs

class ViewModel
  constructor: ->
    $.ajax({url: '#.json', type: 'GET', dataType: 'json'})
    .done @buildModel

  buildModel: (data) =>
    @model = ko.mapping.fromJS(data)
    @model.update = =>
      delete @model.update
      jsonForm = ko.mapping.toJSON(@model)
      $.ajax({url: '#.json', data: jsonForm, type: 'PUT', contentType:"application/json; charset=utf-8", dataType: 'json'})
      .done @buildModel

    ko.applyBindings(@model)

###################################################################

class FormViewModel extends ViewModel
  buildModel: =>
    super()

If I call this:

$(document).bind 'pageinit', =>
  @form = new ViewModel

everything is fine. If I try to inherit

$(document).bind 'pageinit', =>
  @form = new FormViewModel

getting an error:

Uncaught Error: Unable to parse bindings.
Message: ReferenceError: update is not defined;
Bindings value: click: update 

Why ko.applyBindings is not happy with this inheritance?

Upvotes: 3

Views: 931

Answers (1)

David Weldon
David Weldon

Reputation: 64312

Use super instead of super() in FormViewModel's buildModel function.

  • super() means: call the parent method of the same name, without any arguments.
  • super means: call the parent method of the same name, with whatever arguments I received.

So the subclass was always calling the parent buildModel function with data = undefined.

Also note that I don't think you should need to call ko.applyBindings in the buildModel function. The call should only need to happen once for the entire view model.

Upvotes: 2

Related Questions