Knockout extender
Upcoming SlideShare
Loading in...5
×
 

Knockout extender

on

  • 329 views

 

Statistics

Views

Total Views
329
Views on SlideShare
329
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Knockout extender Knockout extender Presentation Transcript

    • Knockout Extender Bryan Lin 2013/11/01
    • Using extenders to augment observables Knockout observables provide the basic features necessary to support reading/writing values and notifying subscribers when that value changes
    • Using extenders to augment observables How to create an extender Using the ko.extenders object ko.extenders.logChange = function(target, option) { target.subscribe(function(newValue) { console.log(option + ": " + newValue); }); return target; }; this.firstName = ko.observable("Bob").extend({logChange: "first name"});
    • Using extenders to augment observables How to create an extender  View: <p><input data-bind="value: myNumberOne" /> (round to whole number)</p> <p><input data-bind="value: myNumberTwo" /> (round to two decimals)</p>
    • ko.extenders.numeric = function(target, precision) { //create a writeable computed observable to intercept writes to our observable var result = ko.computed({ read: target, //always return the original observables value write: function(newValue) { var current = target(), roundingMultiplier = Math.pow(10, precision), newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue), valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier; //only write if it changed if (valueToWrite !== current) { target(valueToWrite); } else { //if the rounded value is the same, but a different value was written, force a notification for the current field if (newValue !== current) { target.notifySubscribers(valueToWrite); } } } }).extend({ notify: 'always' }); //initialize with current value to make sure it is rounded appropriately result(target()); //return the new computed observable return result; }; function AppViewModel(one, two) { this.myNumberOne = ko.observable(one).extend({ numeric: 0 }); this.myNumberTwo = ko.observable(two).extend({ numeric: 2 }); } ko.applyBindings(new AppViewModel(221.2234, 123.4525));
    • References http://knockoutjs.com/ http://jsbin.com/ahelar/49/edit