admin管理员组文章数量:1402995
I have an issue with Knockout where I prototype a user object where the observable properties of my object seem to be overwritten by the last occurrence.
Therefore I cannot use the same object more than once otherwise it will be overwritten.
Although this is hard to explain, see my fiddle.
/
What am I doing wrong? (or is this a bug in Knockout?) How can I fix the problem.
I have an issue with Knockout where I prototype a user object where the observable properties of my object seem to be overwritten by the last occurrence.
Therefore I cannot use the same object more than once otherwise it will be overwritten.
Although this is hard to explain, see my fiddle.
http://jsfiddle/RSEcj/1/
What am I doing wrong? (or is this a bug in Knockout?) How can I fix the problem.
Share Improve this question asked May 9, 2012 at 16:39 Rene PotRene Pot 24.8k7 gold badges70 silver badges92 bronze badges3 Answers
Reset to default 7Because observables are functions and not properties they are represented by a single instance on the object prototype, unlike properties which will be created on the object when they are set.
You could use functional inheritance to achieve what you want.
http://jsfiddle/ypWQN/1/
var User = function(firstName, lastName){
var that = {};
that.firstName = ko.observable(firstName);
that.lastName = lastName;
return that;
};
var Employee = function(firstName, lastName){
var that = User();
that.firstName(firstName);
that.lastName = lastName;
return that;
};
Hope this helps.
Here's a nice solution: http://jsfiddle/magikMaker/RSEcj/19/
It uses the new method inheritsFrom(), credits for this go to http://phrogz/js/classes/OOPinJS2.html
Combined this with the apply() method and an init() method and the magic happens... :-)
var Person = function(firstName, lastName){
this.init = function(firstName, lastName){
this.firstName = ko.observable(firstName);
this.setLastName(lastName);
};
this.setLastName = function(lastName){
this.lastName = lastName;
};
this.init.apply(this, arguments);
};
var Child = function(firstName, lastName){
this.init.apply(this, arguments);
};
Child.inheritsFrom(Person);
Bit late i know, but this might help someone.
Try defining it like this, always works a treat for me
function User(firstName,lastName)
{
this.firstName = ko.observable(firstName);
this.lastName = lastName;
}
function Employee(firstName,lastName)
{
User.apply(this,arguments);
this.firstName(firstName);
this.lastName = lastName;
}
Employee.prototype = Object.create(User.prototype);
Employee.prototype.constructor = Employee;
本文标签: javascriptKnockout issue with prototypical inheritanceStack Overflow
版权声明:本文标题:javascript - Knockout issue with prototypical inheritance - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744607636a2615454.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论