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()
如果我这样称呼:
$(document).bind 'pageinit', =>
@form = new ViewModel
一切都很好。如果我尝试继承
$(document).bind 'pageinit', =>
@form = new FormViewModel
出现错误:
Uncaught Error: Unable to parse bindings.
Message: ReferenceError: update is not defined;
Bindings value: click: update
为什么 ko.applyBindings 对这种继承不满意?
最佳答案
在 FormViewModel
的 buildModel
函数中使用 super
而不是 super()
。
super()
表示:调用父类的同名方法,不带任何参数。super
表示:使用我收到的任何参数调用同名的父方法。
所以子类总是调用父类 buildModel
函数,数据 = undefined
。
另请注意,我认为您不需要在 buildModel
函数中调用 ko.applyBindings
。对于整个 View 模型,调用只需要发生一次。
关于继承和knockoutjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11849277/