Reputation: 4167
can i (and if yes how) create a ko.observable
out of a object.defineproperty
something like this
Strength: ko.observable(
Object.defineProperty(this, "strength", {
get: function () {
return this.level * 2;
},
enumerable: true
});
)
and
<span> str: <span data-bind="text: Strength"></span> / 100 </span>
what im trying to do is update the display of strength
when its called after every level-up
i.e.
+=2
)using Object.defineProperty
i would probably just use ko.computable
, but im wondering if there is a way to do it.
Upvotes: 0
Views: 1148
Reputation: 3439
The Knockout ES5 plugin will do what you need. Although I had to also include the Weakmap shim to make it work.
Upvotes: 1
Reputation: 2656
a bit unclear what you want to achive but I'd go with ko.computed. If you want the subscribers (namely your span) of your Strength
property to be notified (when the level
changes after the initial binding), you should also make level
observable.
if you still want to use defineProperty, I hope this little example suits you (edit: added a button to level up)
function ViewModel() {
var self = this;
self.level=ko.observable(5);
self.really_use_computed = ko.computed(function() {
return self.level() * 2;
});
}
var MyViewModel=new ViewModel();
Object.defineProperty(MyViewModel, "Strength", {
get: function () {
return this.level() * 2;
},
enumerable: true
});
ko.applyBindings(MyViewModel);
please note that Internet Explorer 8 standards mode supports DOM objects but not user-defined objects for the first argument of Object.defineProperty()
and that earlier versions of IE don't support Object.defineProperty()
at all.
Upvotes: 2